diff --git a/logger.go b/logger.go index 5f4b727..50ef243 100644 --- a/logger.go +++ b/logger.go @@ -2,6 +2,7 @@ package gosdk import ( "context" + "fmt" "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/logging" "go.opentelemetry.io/otel/trace" "go.uber.org/zap" @@ -17,6 +18,35 @@ func NewLogger() (*zap.Logger, error) { 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()}