-
Notifications
You must be signed in to change notification settings - Fork 0
/
log.go
63 lines (48 loc) · 1.35 KB
/
log.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
package zaplog
import (
"context"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
type Logger struct {
*zap.Logger
}
var globalLogger *Logger
func StartLogger() error {
config := zap.NewProductionConfig()
config.EncoderConfig.EncodeTime = zapcore.RFC3339TimeEncoder
logger, err := config.Build(zap.AddCaller(), zap.AddCallerSkip(1))
if err != nil {
return err
}
globalLogger = &Logger{Logger: logger}
return nil
}
func GetGlobalLogger() *Logger {
if globalLogger == nil {
_ = StartLogger()
}
return globalLogger
}
func (l *Logger) WithContext(ctx context.Context) *Logger {
traceID := TraceIDFromContext(ctx)
return &Logger{Logger: l.With(zap.String("traceID", traceID))}
}
func TraceIDFromContext(ctx context.Context) string {
if traceID, ok := ctx.Value("traceID").(string); ok {
return traceID
}
return ""
}
func Info(ctx context.Context, message string, fields ...zap.Field) {
GetGlobalLogger().WithContext(ctx).Info(message, fields...)
}
func Debug(ctx context.Context, message string, fields ...zap.Field) {
GetGlobalLogger().WithContext(ctx).Debug(message, fields...)
}
func Error(ctx context.Context, message string, fields ...zap.Field) {
GetGlobalLogger().WithContext(ctx).Error(message, fields...)
}
func Fatal(ctx context.Context, message string, fields ...zap.Field) {
GetGlobalLogger().WithContext(ctx).Fatal(message, fields...)
}