-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogger.go
69 lines (59 loc) · 1.59 KB
/
logger.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
package gosdk
import (
"context"
"fmt"
"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/logging"
"go.opentelemetry.io/otel/trace"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"time"
)
var Level = zapcore.InfoLevel
func SetLogLevel(level string) error {
l, err := zapcore.ParseLevel(level)
if err != nil {
return err
}
Level = l
return nil
}
func NewLogger() (*zap.Logger, error) {
config := zap.NewProductionConfig()
config.Level = zap.NewAtomicLevelAt(Level)
config.EncoderConfig.EncodeTime = zapcore.TimeEncoderOfLayout(time.RFC3339Nano)
config.EncoderConfig.TimeKey = "time"
return config.Build()
}
// InterceptorLogger adapts zap logger to interceptor logger.
// This code is simple enough to be copied and not imported.
func InterceptorLogger(l *zap.Logger) logging.Logger {
return logging.LoggerFunc(func(ctx context.Context, lvl logging.Level, msg string, fields ...any) {
f := make([]zap.Field, 0, len(fields)/2)
for i := 0; i < len(fields); i += 2 {
i := logging.Fields(fields).Iterator()
if i.Next() {
k, v := i.At()
f = append(f, zap.Any(k, v))
}
}
l = l.WithOptions(zap.AddCallerSkip(1)).With(f...)
switch lvl {
case logging.LevelDebug:
l.Debug(msg)
case logging.LevelInfo:
l.Info(msg)
case logging.LevelWarn:
l.Warn(msg)
case logging.LevelError:
l.Error(msg)
default:
panic(fmt.Sprintf("unknown level %v", lvl))
}
})
}
func LogWithTraceID(ctx context.Context) logging.Fields {
if span := trace.SpanContextFromContext(ctx); span.IsSampled() {
return logging.Fields{"traceID", span.TraceID().String()}
}
return nil
}