-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogging.go
More file actions
53 lines (40 loc) · 904 Bytes
/
logging.go
File metadata and controls
53 lines (40 loc) · 904 Bytes
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
package gocommon
import (
"context"
"os"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
const (
LoggerKey = "K_LOGGER"
)
func CreateLogger() *zap.Logger {
debug := GetBoolEnvWithDefault("DEBUG", false)
pe := zap.NewProductionEncoderConfig()
pe.EncodeTime = zapcore.ISO8601TimeEncoder
level := zap.InfoLevel
if debug {
level = zap.DebugLevel
}
var encoder zapcore.Encoder
if IsDocker() {
encoder = zapcore.NewJSONEncoder(pe)
} else {
encoder = zapcore.NewConsoleEncoder(pe)
}
core := zapcore.NewTee(
zapcore.NewCore(encoder, zapcore.AddSync(os.Stdout), level),
)
l := zap.New(core)
return l
}
func CtxWithLogger(ctx context.Context) context.Context {
return context.WithValue(ctx, LoggerKey, CreateLogger())
}
func LogWithCtx(ctx context.Context) *zap.Logger {
logger, ok := ctx.Value(LoggerKey).(*zap.Logger)
if !ok {
return CreateLogger()
}
return logger
}