-
Notifications
You must be signed in to change notification settings - Fork 3
/
logger.go
239 lines (197 loc) · 4.16 KB
/
logger.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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
package logger
import (
"context"
"errors"
"io"
"sync/atomic"
"time"
)
// TimeFormat is the format that times will be added in.
//
// TimeFormat defaults to unix time.
var TimeFormat = TimeFormatUnix
// Time formats.
const (
TimeFormatUnix = ""
TimeFormatISO8601 = "2006-01-02T15:04:05-0700"
)
// List of predefined log Levels.
const (
Disabled Level = iota
Crit
Error
Warn
Info
Debug
Trace
)
// Level represents the predefined log level.
type Level int
// LevelFromString converts a string to Level.
func LevelFromString(lvl string) (Level, error) {
switch lvl {
case "trace", "trce":
return Trace, nil
case "debug", "dbug":
return Debug, nil
case "info":
return Info, nil
case "warn":
return Warn, nil
case "error", "eror":
return Error, nil
case "crit":
return Crit, nil
default:
return 0, errors.New("unknown level " + lvl)
}
}
// String returns the string representation of the level.
func (l Level) String() string {
switch l {
case Trace:
return "trce"
case Debug:
return "dbug"
case Info:
return "info"
case Warn:
return "warn"
case Error:
return "eror"
case Crit:
return "crit"
default:
return "unkn"
}
}
// Field is a context field.
type Field func(*Event)
// Logger is a logger.
type Logger struct {
w io.Writer
isDiscard bool
fmtr Formatter
timeFn func() time.Time
ctx []byte
lvl Level
}
// New creates a new Logger.
func New(w io.Writer, fmtr Formatter, lvl Level) *Logger {
isDiscard := w == io.Discard
return &Logger{
w: w,
isDiscard: isDiscard,
fmtr: fmtr,
lvl: lvl,
}
}
// WithTimestamp adds a timestamp to each log lone. Sub-loggers
// will inherit the timestamp.
//
// WithTimestamp is not thread safe.
func (l *Logger) WithTimestamp() (cancel func()) {
if l.timeFn != nil {
return func() {}
}
ctx, cancel := context.WithCancel(context.Background())
var ts atomic.Value
ts.Store(time.Now())
go func() {
tick := time.NewTicker(100 * time.Millisecond)
defer tick.Stop()
for {
select {
case <-ctx.Done():
return
case <-tick.C:
ts.Store(time.Now())
}
}
}()
l.timeFn = func() time.Time {
t := ts.Load().(time.Time)
return t
}
return cancel
}
// With returns a new Logger with the given context.
func (l *Logger) With(ctx ...Field) *Logger {
e := newEvent(l.fmtr)
defer putEvent(e)
e.buf.Write(l.ctx)
for _, field := range ctx {
field(e)
}
b := make([]byte, e.buf.Len())
copy(b, e.buf.Bytes())
return &Logger{
w: l.w,
isDiscard: l.isDiscard,
fmtr: l.fmtr,
timeFn: l.timeFn,
lvl: l.lvl,
ctx: b,
}
}
// Trace logs a trace message, intended for fine grained debug messages.
func (l *Logger) Trace(msg string, ctx ...Field) {
l.write(msg, Trace, ctx)
}
// Debug logs a debug message.
func (l *Logger) Debug(msg string, ctx ...Field) {
l.write(msg, Debug, ctx)
}
// Info logs an informational message.
func (l *Logger) Info(msg string, ctx ...Field) {
l.write(msg, Info, ctx)
}
// Warn logs a warning message.
func (l *Logger) Warn(msg string, ctx ...Field) {
l.write(msg, Warn, ctx)
}
// Error logs an error message.
func (l *Logger) Error(msg string, ctx ...Field) {
l.write(msg, Error, ctx)
}
// Crit logs a critical message.
func (l *Logger) Crit(msg string, ctx ...Field) {
l.write(msg, Crit, ctx)
}
type writerFunc func([]byte) (int, error)
func (fn writerFunc) Write(p []byte) (n int, err error) {
return fn(p)
}
// Writer returns an io.Writer that writes at the given level.
// This can be used as a writer with the standard log library.
func (l *Logger) Writer(lvl Level) io.Writer {
return writerFunc(func(p []byte) (n int, err error) {
n = len(p)
if l.isDiscard {
return n, nil
}
if n > 0 && p[n-1] == '\n' {
p = p[:n-1]
}
l.write(string(p), lvl, nil)
return n, nil
})
}
func (l *Logger) write(msg string, lvl Level, ctx []Field) {
if l.isDiscard || lvl > l.lvl {
return
}
e := newEvent(l.fmtr)
var ts time.Time
if l.timeFn != nil {
ts = l.timeFn()
}
e.fmtr.WriteMessage(e.buf, ts, lvl, msg)
e.buf.Write(l.ctx)
for _, field := range ctx {
field(e)
}
e.fmtr.AppendEndMarker(e.buf)
_, _ = l.w.Write(e.buf.Bytes())
putEvent(e)
}