-
Notifications
You must be signed in to change notification settings - Fork 388
/
zap.go
75 lines (62 loc) · 2.41 KB
/
zap.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
package log
import (
"io"
"log/slog"
"go.uber.org/zap"
"go.uber.org/zap/exp/zapslog"
"go.uber.org/zap/zapcore"
)
// NewZapLoggerFn is the zap logger init declaration
type NewZapLoggerFn func(w io.Writer, level zapcore.Level, opts ...zap.Option) *zap.Logger
// GetZapLoggerFn returns the appropriate init callback
// for the zap logger, given the requested format
func GetZapLoggerFn(format Format) NewZapLoggerFn {
switch format {
case JSONFormat:
return NewZapJSONLogger
case TestingFormat:
return NewZapTestingLogger
default:
return NewZapConsoleLogger
}
}
// NewZapJSONLogger creates a zap logger with a JSON encoder for production use.
func NewZapJSONLogger(w io.Writer, level zapcore.Level, opts ...zap.Option) *zap.Logger {
// Build encoder config
jsonConfig := zap.NewProductionEncoderConfig()
// Build encoder
enc := zapcore.NewJSONEncoder(jsonConfig)
return NewZapLogger(enc, w, level, opts...)
}
// NewZapConsoleLogger creates a zap logger with a console encoder for development use.
func NewZapConsoleLogger(w io.Writer, level zapcore.Level, opts ...zap.Option) *zap.Logger {
// Build encoder config
consoleConfig := zap.NewDevelopmentEncoderConfig()
consoleConfig.EncodeLevel = stableWidthCapitalColorLevelEncoder
consoleConfig.EncodeName = stableWidthNameEncoder
// Build encoder
enc := zapcore.NewConsoleEncoder(consoleConfig)
return NewZapLogger(enc, w, level, opts...)
}
// NewZapTestingLogger creates a zap logger with a console encoder optimized for testing.
func NewZapTestingLogger(w io.Writer, level zapcore.Level, opts ...zap.Option) *zap.Logger {
// Build encoder config
consoleConfig := zap.NewDevelopmentEncoderConfig()
consoleConfig.TimeKey = ""
consoleConfig.EncodeLevel = stableWidthCapitalLevelEncoder
consoleConfig.EncodeName = stableWidthNameEncoder
// Build encoder
enc := zapcore.NewConsoleEncoder(consoleConfig)
return NewZapLogger(enc, w, level, opts...)
}
// NewZapLogger creates a new zap logger instance, for the given level, writer and zap encoder.
func NewZapLogger(enc zapcore.Encoder, w io.Writer, level zapcore.Level, opts ...zap.Option) *zap.Logger {
ws := zapcore.AddSync(w)
// Create zap core
core := zapcore.NewCore(enc, ws, zap.NewAtomicLevelAt(level))
return zap.New(core, opts...)
}
// ZapLoggerToSlog wraps the given zap logger to an log/slog Logger
func ZapLoggerToSlog(logger *zap.Logger) *slog.Logger {
return slog.New(zapslog.NewHandler(logger.Core()))
}