-
Notifications
You must be signed in to change notification settings - Fork 34
/
logging.go
139 lines (111 loc) · 2.45 KB
/
logging.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
package logging
import (
"fmt"
"sync"
"github.com/scrapli/scrapligo/util"
)
const (
// Debug is the debug log level.
Debug = "debug"
// Info is the info(rmational) log level.
Info = "info"
// Critical is the critical log level.
Critical = "critical"
)
// NewInstance returns a new logging Instance.
func NewInstance(opts ...util.Option) (*Instance, error) {
i := &Instance{
Level: Info,
Formatter: DefaultFormatter,
Loggers: nil,
}
for _, o := range opts {
err := o(i)
if err != nil {
return nil, err
}
}
return i, nil
}
// Instance is a simple logging object.
type Instance struct {
Level string
Formatter func(string, string) string
Loggers []func(...interface{})
}
// Emit "emits" a logging message m to all the loggers in the Instance.
func (i *Instance) Emit(m interface{}) {
wg := sync.WaitGroup{}
for _, f := range i.Loggers {
wg.Add(1)
lf := f
go func() {
lf(m)
wg.Done()
}()
}
wg.Wait()
}
func (i *Instance) shouldLog(l string) bool {
if len(i.Loggers) == 0 {
return false
}
switch i.Level {
case Debug:
return true
case Info:
switch l {
case Info, Critical:
return true
default:
return false
}
case Critical:
if l == Critical {
return true
}
}
return false
}
// Debug accepts a Debug level log message with no formatting.
func (i *Instance) Debug(f string) {
if !i.shouldLog(Debug) {
return
}
i.Emit(i.Formatter(Debug, f))
}
// Debugf accepts a Debug level log message normal fmt.Sprintf type formatting.
func (i *Instance) Debugf(f string, a ...interface{}) {
if !i.shouldLog(Debug) {
return
}
i.Emit(i.Formatter(Debug, fmt.Sprintf(f, a...)))
}
// Info accepts an Info level log message with no formatting.
func (i *Instance) Info(f string) {
if !i.shouldLog(Info) {
return
}
i.Emit(i.Formatter(Info, f))
}
// Infof accepts an Info level log message normal fmt.Sprintf type formatting.
func (i *Instance) Infof(f string, a ...interface{}) {
if !i.shouldLog(Info) {
return
}
i.Emit(i.Formatter(Info, fmt.Sprintf(f, a...)))
}
// Critical accepts a Critical level log message with no formatting.
func (i *Instance) Critical(f string) {
if !i.shouldLog(Critical) {
return
}
i.Emit(i.Formatter(Critical, f))
}
// Criticalf accepts a Critical level log message normal fmt.Sprintf type formatting.
func (i *Instance) Criticalf(f string, a ...interface{}) {
if !i.shouldLog(Critical) {
return
}
i.Emit(i.Formatter(Critical, fmt.Sprintf(f, a...)))
}