This repository was archived by the owner on Jun 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlogger.go
293 lines (261 loc) · 8 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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
package rz
import (
"fmt"
"os"
"runtime"
"strconv"
"sync"
"time"
"github.com/skerkour/rz/internal/json"
)
// A Logger represents an active logging object that generates lines
// of JSON output to an io.Writer. Each logging operation makes a single
// call to the Writer's Write method. There is no guaranty on access
// serialization to the Writer. If your Writer is not thread safe,
// you may consider a sync wrapper.
type Logger struct {
writer LevelWriter
stack bool
caller bool
timestamp bool
level LogLevel
sampler LogSampler
context []byte
hooks []LogHook
timestampFieldName string
levelFieldName string
messageFieldName string
errorFieldName string
callerFieldName string
callerSkipFrameCount int
errorStackFieldName string
timeFieldFormat string
formatter LogFormatter
timestampFunc func() time.Time
contextMutex *sync.Mutex
encoder Encoder
}
// New creates a root logger with given options. If the output writer implements
// the LevelWriter interface, the WriteLevel method will be called instead of the Write
// one. Default writer is os.Stdout
//
// Each logging operation makes a single call to the Writer's Write method. There is no
// guaranty on access serialization to the Writer. If your Writer is not thread safe,
// you may consider using sync wrapper.
func New(options ...LoggerOption) Logger {
logger := Logger{
writer: levelWriterAdapter{os.Stdout},
level: DebugLevel,
timestamp: true,
timestampFieldName: DefaultTimestampFieldName,
levelFieldName: DefaultLevelFieldName,
messageFieldName: DefaultMessageFieldName,
errorFieldName: DefaultErrorFieldName,
callerFieldName: DefaultCallerFieldName,
callerSkipFrameCount: DefaultCallerSkipFrameCount,
errorStackFieldName: DefaultErrorStackFieldName,
timeFieldFormat: DefaultTimeFieldFormat,
timestampFunc: DefaultTimestampFunc,
contextMutex: &sync.Mutex{},
encoder: json.Encoder{},
}
return logger.With(options...)
}
// Nop returns a disabled logger for which all operation are no-op.
func Nop() Logger {
return New(Writer(nil), Level(Disabled))
}
// With create a new copy of the logger and apply all the options to the new logger
func (l Logger) With(options ...LoggerOption) Logger {
oldContext := l.context
l.context = make([]byte, 0, 500)
l.contextMutex = &sync.Mutex{}
if oldContext != nil {
l.context = append(l.context, oldContext...)
}
for _, option := range options {
option(&l)
}
return l
}
// GetLevel returns the current log level.
func (l *Logger) GetLevel() LogLevel {
return l.level
}
// LogWithLevel logs a new message with the given level.
func (l *Logger) LogWithLevel(level LogLevel, message string, fields ...Field) {
l.logEvent(level, message, nil, fields)
}
// Debug logs a new message with debug level.
func (l *Logger) Debug(message string, fields ...Field) {
l.logEvent(DebugLevel, message, nil, fields)
}
// Info logs a new message with info level.
func (l *Logger) Info(message string, fields ...Field) {
l.logEvent(InfoLevel, message, nil, fields)
}
// Warn logs a new message with warn level.
func (l *Logger) Warn(message string, fields ...Field) {
l.logEvent(WarnLevel, message, nil, fields)
}
// Error logs a message with error level.
func (l *Logger) Error(message string, fields ...Field) {
l.logEvent(ErrorLevel, message, nil, fields)
}
// Fatal logs a new message with fatal level. The os.Exit(1) function
// is then called, which terminates the program immediately.
func (l *Logger) Fatal(message string, fields ...Field) {
l.logEvent(FatalLevel, message, func(msg string) { os.Exit(1) }, fields)
}
// Panic logs a new message with panic level. The panic() function
// is then called, which stops the ordinary flow of a goroutine.
func (l *Logger) Panic(message string, fields ...Field) {
l.logEvent(PanicLevel, message, func(msg string) { panic(msg) }, fields)
}
// Log logs a new message with no level. Setting GlobalLevel to Disabled
// will still disable events produced by this method.
func (l *Logger) Log(message string, fields ...Field) {
l.logEvent(NoLevel, message, nil, fields)
}
// NewDict creates an Event to be used with the Dict method.
// Call usual field methods like Str, Int etc to add fields to this
// event and give it as argument the *Event.Dict method.
func (l *Logger) NewDict(fields ...Field) *Event {
e := newEvent(nil, 0)
copyInternalLoggerFieldsToEvent(l, e)
e.Append(fields...)
return e
}
// Write implements the io.Writer interface. This is useful to set as a writer
// for the standard library log.
//
// log := rz.New()
// stdlog.SetFlags(0)
// stdlog.SetOutput(log)
// stdlog.Print("hello world")
func (l Logger) Write(p []byte) (n int, err error) {
n = len(p)
if n > 0 && p[n-1] == '\n' {
// Trim CR added by stdlog.
p = p[0 : n-1]
}
l.Log(string(p))
return
}
func (l *Logger) logEvent(level LogLevel, message string, done func(string), fields []Field) {
enabled := l.should(level)
if !enabled {
return
}
e := newEvent(l.writer, level)
e.ch = l.hooks
copyInternalLoggerFieldsToEvent(l, e)
if level != NoLevel {
e.string(e.levelFieldName, level.String())
}
if l.context != nil && len(l.context) > 0 {
e.buf = enc.AppendObjectData(e.buf, l.context)
}
for i := range fields {
fields[i](e)
}
writeEvent(e, message, done)
}
func writeEvent(e *Event, msg string, done func(string)) {
// run hooks
if len(e.ch) > 0 {
e.ch[0].Run(e, e.level, msg)
if len(e.ch) > 1 {
for _, hook := range e.ch[1:] {
hook.Run(e, e.level, msg)
}
}
}
if done != nil {
defer done(msg)
}
// if hooks didn't disabled our event, continue
if e.level != Disabled {
var err error
if e.timestamp {
e.buf = enc.AppendTime(enc.AppendKey(e.buf, e.timestampFieldName), e.timestampFunc(), e.timeFieldFormat)
}
if msg != "" {
e.buf = enc.AppendString(enc.AppendKey(e.buf, e.messageFieldName), msg)
}
if e.caller {
_, file, line, ok := runtime.Caller(e.callerSkipFrameCount)
if ok {
e.buf = enc.AppendString(enc.AppendKey(e.buf, e.callerFieldName), file+":"+strconv.Itoa(line))
}
}
// end json payload
e.buf = enc.AppendEndMarker(e.buf)
e.buf = enc.AppendLineBreak(e.buf)
if e.formatter != nil {
e.buf, err = e.formatter(e)
}
if e.w != nil {
_, err = e.w.WriteLevel(e.level, e.buf)
}
putEvent(e)
if err != nil {
if ErrorHandler != nil {
ErrorHandler(err)
} else {
fmt.Fprintf(os.Stderr, "rz: could not write event: %v\n", err)
}
}
}
}
// should returns true if the log event should be logged.
func (l *Logger) should(lvl LogLevel) bool {
if lvl < l.level {
return false
}
if l.sampler != nil {
return l.sampler.Sample(lvl)
}
return true
}
// Append the fields to the internal logger's context.
// It does not create a new copy of the logger and rely on a mutex to enable thread safety,
// so `With(Fields(fields...))` often is preferable.
func (l *Logger) Append(fields ...Field) {
e := newEvent(l.writer, l.level)
e.buf = nil
copyInternalLoggerFieldsToEvent(l, e)
for i := range fields {
fields[i](e)
}
l.contextMutex.Lock()
if e.stack != l.stack {
l.stack = e.stack
}
if e.caller != l.caller {
l.caller = e.caller
}
if e.timestamp != l.timestamp {
l.timestamp = e.timestamp
}
if e.buf != nil {
l.context = enc.AppendObjectData(l.context, e.buf)
}
l.contextMutex.Unlock()
}
func copyInternalLoggerFieldsToEvent(l *Logger, e *Event) {
e.stack = l.stack
e.caller = l.caller
e.timestamp = l.timestamp
e.timestampFieldName = l.timestampFieldName
e.levelFieldName = l.levelFieldName
e.messageFieldName = l.messageFieldName
e.errorFieldName = l.errorFieldName
e.callerFieldName = l.callerFieldName
e.timeFieldFormat = l.timeFieldFormat
e.errorStackFieldName = l.errorStackFieldName
e.callerSkipFrameCount = l.callerSkipFrameCount
e.formatter = l.formatter
e.timestampFunc = l.timestampFunc
e.encoder = l.encoder
}