/
logging.go
382 lines (327 loc) · 9.51 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
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
// Package logging implements support for structured logging.
//
// This package is inspired heavily by go-logging, kit/log and the
// tendermint libs/log packages, and is oriented towards making
// the structured logging experience somewhat easier to use.
package logging
import (
"fmt"
"io"
"sort"
"strings"
"sync"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
ipfsLog "github.com/ipfs/go-log/v2"
"github.com/spf13/pflag"
)
var (
backend = logBackend{
baseLogger: log.NewNopLogger(),
defaultLevel: LevelError,
}
_ pflag.Value = (*Level)(nil)
_ pflag.Value = (*Format)(nil)
)
// Format is a logging format.
type Format uint
const (
// FmtLogfmt is the "logfmt" logging format.
FmtLogfmt Format = iota
// FmtJSON is the JSON logging format.
FmtJSON
)
// String returns the string representation of a Format.
func (f *Format) String() string {
switch *f {
case FmtLogfmt:
return "logfmt"
case FmtJSON:
return "JSON"
default:
panic("logging: unsupported format")
}
}
// Set sets the Format to the value specified by the provided string.
func (f *Format) Set(s string) error {
switch strings.ToUpper(s) {
case "LOGFMT":
*f = FmtLogfmt
case "JSON":
*f = FmtJSON
default:
return fmt.Errorf("logging: invalid log format: '%s'", s)
}
return nil
}
// Type returns the list of supported Formats.
func (f *Format) Type() string {
return "[logfmt,JSON]"
}
// Level is a log level.
type Level uint
const (
// LevelDebug is the log level for debug messages.
LevelDebug Level = iota
// LevelInfo is the log level for informative messages.
LevelInfo
// LevelWarn is the log level for warning messages.
LevelWarn
// LevelError is the log level for error messages.
LevelError
)
func (l Level) toOption() level.Option {
switch l {
case LevelDebug:
return level.AllowDebug()
case LevelInfo:
return level.AllowInfo()
case LevelWarn:
return level.AllowWarn()
case LevelError:
return level.AllowError()
default:
panic("logging: unsupported log level")
}
}
// String returns the string representation of a Level.
func (l *Level) String() string {
switch *l {
case LevelDebug:
return "DEBUG"
case LevelInfo:
return "INFO"
case LevelWarn:
return "WARN"
case LevelError:
return "ERROR"
default:
panic("logging: unsupported log level")
}
}
// Set sets the Level to the value specified by the provided string.
func (l *Level) Set(s string) error {
switch strings.ToUpper(s) {
case "DEBUG":
*l = LevelDebug
case "INFO":
*l = LevelInfo
case "WARN":
*l = LevelWarn
case "ERROR":
*l = LevelError
default:
return fmt.Errorf("logging: invalid log level: '%s'", s)
}
return nil
}
// Type returns the list of supported Levels.
func (l *Level) Type() string {
return "[DEBUG,INFO,WARN,ERROR]"
}
// Logger is a logger instance.
type Logger struct {
logger log.Logger
level Level
module string
}
// Debug logs the message and key value pairs at the Debug log level.
func (l *Logger) Debug(msg string, keyvals ...interface{}) {
if l.level > LevelDebug {
return
}
keyvals = append([]interface{}{"msg", msg}, keyvals...)
_ = level.Debug(l.logger).Log(keyvals...)
}
// Info logs the message and key value pairs at the Info log level.
func (l *Logger) Info(msg string, keyvals ...interface{}) {
if l.level > LevelInfo {
return
}
keyvals = append([]interface{}{"msg", msg}, keyvals...)
_ = level.Info(l.logger).Log(keyvals...)
}
// Warn logs the message and key value pairs at the Warn log level.
func (l *Logger) Warn(msg string, keyvals ...interface{}) {
if l.level > LevelWarn {
return
}
keyvals = append([]interface{}{"msg", msg}, keyvals...)
_ = level.Warn(l.logger).Log(keyvals...)
}
// Error logs the message and key value pairs at the Error log level.
func (l *Logger) Error(msg string, keyvals ...interface{}) {
if l.level > LevelError {
return
}
keyvals = append([]interface{}{"msg", msg}, keyvals...)
_ = level.Error(l.logger).Log(keyvals...)
}
// With returns a clone of the logger with the provided key/value pairs
// added via log.WithPrefix.
func (l *Logger) With(keyvals ...interface{}) *Logger {
return &Logger{
logger: log.With(l.logger, keyvals...),
level: l.level,
}
}
// GetLevel returns the current global log level.
func GetLevel() Level {
return backend.defaultLevel
}
// GetLogger creates a new logger instance with the specified module.
//
// This may be called from any point, including before Initialize is
// called, allowing for the construction of a package level Logger.
func GetLogger(module string) *Logger {
return backend.getLogger(module, 0)
}
// GetLoggerEx creates a new logger instance with the specified module,
// using the specified extra levels of stack unwinding when determining
// a caller.
//
// The GetLogger call is equivalent to GetLoggerEx with an extraUnwind
// of 0. This routine is primarily intended to facilitate writing
// additional logging wrappers.
func GetLoggerEx(module string, extraUnwind int) *Logger {
return backend.getLogger(module, extraUnwind)
}
// GetBaseLogger creates a new non-prefixed logger instance with the
// specified module.
//
// The returned logger will not pre-include any log fields (aka prefixes)
// except for the module name. Its level will be set in accordance
// with the global config, which can be per-module.
//
// This may be called from any point, including before Initialize is
// called, allowing for the construction of a package level Logger.
func GetBaseLogger(module string) *Logger {
return backend.getBaseLogger(module)
}
// Initialize initializes the logging backend to write to the provided
// Writer with the given format and log levels specified for each
// module. If the requested module is not given, default level is
// taken. If the Writer is nil, all log output will be silently discarded.
func Initialize(w io.Writer, format Format, defaultLvl Level, moduleLvls map[string]Level) error {
backend.Lock()
defer backend.Unlock()
if backend.initialized {
return fmt.Errorf("logging: already initialized")
}
var logger log.Logger = backend.baseLogger
if w != nil {
w = log.NewSyncWriter(w)
switch format {
case FmtLogfmt:
logger = log.NewLogfmtLogger(w)
case FmtJSON:
logger = log.NewJSONLogger(w)
default:
return fmt.Errorf("logging: unsupported log format: %v", format)
}
}
logger = level.NewFilter(logger, defaultLvl.toOption())
backend.baseLogger = logger
backend.moduleLevels = moduleLvls
backend.defaultLevel = defaultLvl
backend.initialized = true
// Swap all the early loggers to the initialized backend.
for _, l := range backend.earlyLoggers {
l.swapLogger.Swap(backend.baseLogger)
// Re-evaluate log level.
// NOTE: This introduces a potential race condition if loggers are used
// before the logging system is initialized. Protecting the log
// level with a mutex just for this one case seems overkill.
backend.setupLogLevelLocked(l.logger)
}
backend.earlyLoggers = nil
// libp2p/IPFS uses yet another logging library, that appears to be a
// wrapper around zap.
ipfsLogger := newZapCore(log.With(logger, "ts", log.DefaultTimestampUTC), "libp2p", 7)
backend.setupLogLevelLocked(ipfsLogger.logger)
// Update the ipfs core logger.
ipfsLog.SetPrimaryCore(ipfsLogger)
// Enable all logs on the ipfs logger.
// zapCore will filter logs based on the configured logging level of the oasis node.
ipfsLog.SetDebugLogging()
return nil
}
type earlyLogger struct {
swapLogger *log.SwapLogger
logger *Logger
}
type logBackend struct {
sync.Mutex
baseLogger log.Logger
earlyLoggers []*earlyLogger
defaultLevel Level
moduleLevels map[string]Level
initialized bool
}
func (b *logBackend) setupLogLevelLocked(l *Logger) {
// Check, whether there is a specific logging level set for the module.
// The longest prefix match of the module name provided in the config file will be taken.
// Otherwise, fallback to level defined by "default" key.
modulePrefixes := make([]string, 0, len(b.moduleLevels))
for k := range b.moduleLevels {
modulePrefixes = append(modulePrefixes, k)
}
sort.Sort(sort.Reverse(sort.StringSlice(modulePrefixes)))
lvl := b.defaultLevel
for _, k := range modulePrefixes {
if strings.HasPrefix(l.module, k) {
lvl = b.moduleLevels[k]
break
}
}
l.level = lvl
}
func (b *logBackend) getLogger(module string, extraUnwind int) *Logger {
// The default unwind depth is as log.DefaultCaller, with an
// additional level of stack unwinding due to this module's
// leveling wrapper.
const defaultUnwind = 4
b.Lock()
defer b.Unlock()
logger := b.baseLogger
if !b.initialized {
logger = &log.SwapLogger{}
}
prefixes := []interface{}{
"ts", log.DefaultTimestampUTC,
"caller", log.Caller(defaultUnwind + extraUnwind),
"module", module,
}
l := &Logger{
logger: log.WithPrefix(logger, prefixes...),
module: module,
}
b.setupLogLevelLocked(l)
if !b.initialized {
// Stash the logger so that it can be instantiated once logging
// is actually initialized.
sLog := logger.(*log.SwapLogger)
b.earlyLoggers = append(b.earlyLoggers, &earlyLogger{swapLogger: sLog, logger: l})
}
return l
}
func (b *logBackend) getBaseLogger(module string) *Logger {
b.Lock()
defer b.Unlock()
logger := b.baseLogger
if !b.initialized {
logger = &log.SwapLogger{}
}
l := &Logger{
logger: log.WithPrefix(logger, "module", module),
module: module,
}
b.setupLogLevelLocked(l)
if !b.initialized {
// Stash the logger so that it can be instantiated once logging
// is actually initialized.
sLog := logger.(*log.SwapLogger)
b.earlyLoggers = append(b.earlyLoggers, &earlyLogger{swapLogger: sLog, logger: l})
}
return l
}