-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlog.go
More file actions
318 lines (269 loc) · 8.58 KB
/
log.go
File metadata and controls
318 lines (269 loc) · 8.58 KB
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
// Package log is an wrapper package that exposes underlying logger instance.
package log
import (
"context"
"log"
"os"
"sort"
"time"
"go.opentelemetry.io/otel/trace"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
// Log levels as constants.
const (
LevelInfo = "info"
LevelWarn = "warn"
LevelDebug = "debug"
LevelError = "error"
LevelFatal = "fatal"
)
// declare default logger
var logger Logger
// GetZap returns an instance of the underlying Zap logger.
func GetZap() *zap.Logger {
return logger.(*Log).zap
}
// initialize logger during package initialization
func init() {
lgr, err := New()
if err != nil {
log.Panic(err)
}
logger = lgr
}
// Debug logs a message with the "debug" severity level.
// It takes a message and zero or more fields.
func Debug(msg any, fds ...Field) {
logger.Debug(msg, fds...)
}
// Info logs a message with the "info" severity level.
// It takes a message and zero or more fields.
func Info(msg any, fds ...Field) {
logger.Info(msg, fds...)
}
// Warn logs a message with the "warn" severity level.
// It takes a message and zero or more fields.
func Warn(msg any, fds ...Field) {
logger.Warn(msg, fds...)
}
// Error logs a message with the "error" severity level.
// It takes an error and zero or more fields.
func Error(msg any, fds ...Field) {
logger.Error(msg, fds...)
}
// Fatal logs a message with the "fatal" severity level.
// It takes a message and zero or more fields.
// Also it will exit the program with `1“ exit code.
func Fatal(msg any, fds ...Field) {
logger.Fatal(msg, fds...)
}
// Panic logs a message with the "panic" severity level.
// It takes a message and zero or more fields.
// Also it will panic.
func Panic(msg any, fds ...Field) {
logger.Panic(msg, fds...)
}
// Sync calls the underlying Core's Sync method, flushing any buffered log
// entries. Applications should take care to call Sync before exiting.
func Sync() error {
return logger.Sync()
}
// InfoLogger is an interface for logging messages with the "info" severity level.
type InfoLogger interface {
Info(msg any, fds ...Field)
}
// WarnLogger is an interface for logging messages with the "warn" severity level.
type WarnLogger interface {
Warn(msg any, fds ...Field)
}
// DebugLogger is an interface for logging messages with the "debug" severity level.
type DebugLogger interface {
Debug(msg any, fds ...Field)
}
// ErrorLogger is an interface for logging messages with the "error" severity level.
type ErrorLogger interface {
Error(msg any, fds ...Field)
}
// FatalLogger is an interface for logging messages with the "fatal" severity level.
type FatalLogger interface {
Fatal(msg any, fds ...Field)
}
// PanicLogger is an interface for logging messages with the "panic" severity level.
type PanicLogger interface {
Panic(msg any, fds ...Field)
}
// Synchronizer is an interface that exposes Sync() method.
type Synchronizer interface {
Sync() error
}
// Logger is an interface that encompasses all the different severity levels.
type Logger interface {
InfoLogger
WarnLogger
DebugLogger
ErrorLogger
FatalLogger
PanicLogger
Synchronizer
}
// Field is an type to pass additional values to the log function.
type Field = zap.Field
// Any creates a new `Field` that associates a key with an arbitrary value.
// It takes a string key and an interface{} value, and returns a `Field`.
func Any(key string, val any) Field {
return zap.Any(key, val)
}
// Tip returns a `Field` with the given value, using the key "tip".
// This function is a shorthand for creating a field with a message value.
func Tip(val any) Field {
return Any("tip", val)
}
// New creates a new instance of a logger.
func New() (Logger, error) {
cfg := zap.NewProductionConfig()
cfg.EncoderConfig.TimeKey = "time"
cfg.EncoderConfig.EncodeTime = zapcore.RFC3339TimeEncoder
cfg.DisableStacktrace = true
// Set the log level based on the `LOG_LEVEL` environment variable, or use the default of `info`.
switch os.Getenv("LOG_LEVEL") {
case LevelInfo:
cfg.Level.SetLevel(zap.InfoLevel)
case LevelWarn:
cfg.Level.SetLevel(zap.WarnLevel)
case LevelDebug:
cfg.Level.SetLevel(zap.DebugLevel)
case LevelError:
cfg.Level.SetLevel(zap.ErrorLevel)
case LevelFatal:
cfg.Level.SetLevel(zap.FatalLevel)
default:
cfg.Level.SetLevel(zap.InfoLevel)
}
var lgr *zap.Logger
var err error
// Split logging config is experimental, this can be used to disable it.
if os.Getenv("DISABLE_SPLIT_LOGGING") != "" {
lgr, err = BuildDefaultLogger(cfg)
} else {
lgr, err = BuildSplitLogger(cfg)
}
if err != nil {
return nil, err
}
return &Log{zap: lgr}, nil
}
// BuildSplitLogger returns a logger built using the default zap.Config.Build method. Sends all logs to stderr.
func BuildDefaultLogger(cfg zap.Config) (*zap.Logger, error) {
// Build the logger with a caller skip of 2, which causes the logger to report the line number of the calling function.
return cfg.Build(zap.AddCallerSkip(2))
}
// BuildSplitLogger returns a logger that sends some logs to stdout and some to stderr.
func BuildSplitLogger(cfg zap.Config) (*zap.Logger, error) {
warnAndUp := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
return lvl >= zapcore.WarnLevel && cfg.Level.Enabled(lvl)
})
lessThanWarn := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
return lvl < zapcore.WarnLevel && cfg.Level.Enabled(lvl)
})
encoder := zapcore.NewJSONEncoder(cfg.EncoderConfig)
core := zapcore.NewTee(
zapcore.NewCore(encoder, zapcore.Lock(os.Stderr), warnAndUp),
zapcore.NewCore(encoder, zapcore.Lock(os.Stdout), lessThanWarn),
)
opts, err := buildCfgOptions(cfg)
if err != nil {
return nil, err
}
logger := zap.New(core, opts...)
// Build the logger with a caller skip of 2, which causes the logger to report the line number of the calling function.
logger = logger.WithOptions(zap.AddCallerSkip(2))
return logger, nil
}
// buildCfgOptions replicates the internal zap.config.buildOptions(), which we can't use if we want to split
// logs into stdout and stderr.
func buildCfgOptions(cfg zap.Config) ([]zap.Option, error) {
// Sink for internal logger errors
errSink, _, err := zap.Open("stderr")
if err != nil {
return nil, err
}
opts := []zap.Option{zap.ErrorOutput(errSink)}
opts = append(opts, zap.AddCaller())
if scfg := cfg.Sampling; scfg != nil {
opts = append(opts, zap.WrapCore(func(core zapcore.Core) zapcore.Core {
var samplerOpts []zapcore.SamplerOption
if scfg.Hook != nil {
samplerOpts = append(samplerOpts, zapcore.SamplerHook(scfg.Hook))
}
return zapcore.NewSamplerWithOptions(
core,
time.Second,
cfg.Sampling.Initial,
cfg.Sampling.Thereafter,
samplerOpts...,
)
}))
}
if len(cfg.InitialFields) > 0 {
fs := make([]Field, 0, len(cfg.InitialFields))
keys := make([]string, 0, len(cfg.InitialFields))
for k := range cfg.InitialFields {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
fs = append(fs, Any(k, cfg.InitialFields[k]))
}
opts = append(opts, zap.Fields(fs...))
}
return opts, nil
}
// Log is a struct that holds a logger implementation.
type Log struct {
zap *zap.Logger
}
// Debug logs a message with the "debug" severity level.
// It takes a message string and zero or more fields.
func (l *Log) Debug(msg any, fds ...Field) {
l.zap.Debug(getMessage(msg), fds...)
}
// Info logs a message with the "info" severity level.
// It takes a message string and zero or more fields.
func (l *Log) Info(msg any, fds ...Field) {
l.zap.Info(getMessage(msg), fds...)
}
// Warn logs a message with the "warn" severity level.
// It takes a message string and zero or more fields.
func (l *Log) Warn(msg any, fds ...Field) {
l.zap.Warn(getMessage(msg), fds...)
}
// Error logs a message with the "error" severity level.
// It takes a message and zero or more fields.
func (l *Log) Error(msg any, fds ...Field) {
l.zap.Error(getMessage(msg), fds...)
}
// Fatal logs a message with the "fatal" severity level.
// It takes a message and zero or more fields.
// Also it will exit the program with `1“ exit code.
func (l *Log) Fatal(msg any, fds ...Field) {
l.zap.Fatal(getMessage(msg), fds...)
}
// Fatal logs a message with the "panic" severity level.
// It takes a message and zero or more fields.
// Also it will panic.
func (l *Log) Panic(msg any, fds ...Field) {
l.zap.Panic(getMessage(msg), fds...)
}
// Sync calls the underlying Core's Sync method, flushing any buffered log
// entries. Applications should take care to call Sync before exiting.
func (l *Log) Sync() error {
return l.zap.Sync()
}
func TraceID(ctx context.Context) Field {
sc := trace.SpanContextFromContext(ctx)
if !sc.IsValid() {
return Any("traceid", "")
}
return Any("traceid", sc.TraceID().String())
}