/
zap_context.go
44 lines (35 loc) · 888 Bytes
/
zap_context.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
package logger
import (
"context"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
const loggerKey = iota
var Logger *zap.Logger
// Default initializes the logger with the default configuration.
func Default() *zap.Logger {
config := zap.NewProductionConfig()
l, err := config.Build(
zap.AddCaller(),
zap.AddStacktrace(zap.ErrorLevel),
)
if err != nil {
panic(err)
}
Logger = l
return Logger
}
// WithLogger returns a new context with the provided logger.
func WithLogger(ctx context.Context, fields ...zapcore.Field) context.Context {
return context.WithValue(ctx, loggerKey, WithContext(ctx).With(fields...))
}
// WithContext returns a new logger with the provided context.
func WithContext(ctx context.Context) *zap.Logger {
if ctx == nil {
return Logger
}
if ctxLogger, ok := ctx.Value(loggerKey).(*zap.Logger); ok {
return ctxLogger
}
return Logger
}