Skip to content

Commit

Permalink
feat: add intercept log function
Browse files Browse the repository at this point in the history
  • Loading branch information
samithiwat committed Apr 18, 2023
1 parent aaf93d1 commit ce11261
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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()}
Expand Down

0 comments on commit ce11261

Please sign in to comment.