diff --git a/logging/zap/logger.go b/logging/zap/logger.go index e05c66e..2301164 100644 --- a/logging/zap/logger.go +++ b/logging/zap/logger.go @@ -67,7 +67,7 @@ func (l *Logger) CtxLogf(level hlog.Level, ctx context.Context, format string, k l.Logger.CtxLogf(level, ctx, format, kvs...) } else { - l.Logger.Logf(level, format, kvs...) + l.Logger.CtxLogf(level, ctx, format, kvs...) } if !span.IsRecording() { diff --git a/logging/zap/logger_test.go b/logging/zap/logger_test.go index e584107..5d521ce 100644 --- a/logging/zap/logger_test.go +++ b/logging/zap/logger_test.go @@ -20,14 +20,32 @@ import ( "testing" "github.com/cloudwego/hertz/pkg/common/hlog" + hertzzap "github.com/hertz-contrib/logger/zap" "github.com/stretchr/testify/assert" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/exporters/stdout/stdouttrace" sdktrace "go.opentelemetry.io/otel/sdk/trace" + "go.opentelemetry.io/otel/sdk/trace/tracetest" "go.uber.org/zap" ) +func noopProvider(ctx context.Context) func() { + provider := sdktrace.NewTracerProvider() + otel.SetTracerProvider(provider) + + exp := tracetest.NewNoopExporter() + + bsp := sdktrace.NewSimpleSpanProcessor(exp) + provider.RegisterSpanProcessor(bsp) + + return func() { + if err := provider.Shutdown(ctx); err != nil { + panic(err) + } + } +} + func stdoutProvider(ctx context.Context) func() { provider := sdktrace.NewTracerProvider() otel.SetTracerProvider(provider) @@ -127,3 +145,31 @@ func TestLogLevel(t *testing.T) { logger.Debugf("this is a debug log %s", "msg") assert.Contains(t, buf.String(), "this is a debug log") } + +func TestWithExtraKeys(t *testing.T) { + ctx := context.Background() + + buf := new(bytes.Buffer) + + shutdown := noopProvider(ctx) + defer shutdown() + + logger := NewLogger( + WithTraceErrorSpanLevel(zap.WarnLevel), + WithLogger(hertzzap.NewLogger(hertzzap.WithExtraKeys([]hertzzap.ExtraKey{"logger"}))), + ) + defer logger.Sync() + + hlog.SetLogger(logger) + hlog.SetOutput(buf) + + tracer := otel.Tracer("test otel std logger") + + ctx, span := tracer.Start(ctx, "root") + ctx = context.WithValue(ctx, hertzzap.ExtraKey("logger"), "zap") + + hlog.CtxInfof(ctx, "info %s", "this is a info log") + assert.Contains(t, buf.String(), "\"logger\":\"zap\"") + + span.End() +}