Skip to content

Commit

Permalink
Merge pull request #62 from rogerogers/fix/zap-extra
Browse files Browse the repository at this point in the history
fix[zap]: extraKey
  • Loading branch information
GuangmingLuo authored Dec 17, 2024
2 parents 9abdf96 + dc947b1 commit ebef6a5
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
2 changes: 1 addition & 1 deletion logging/zap/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
46 changes: 46 additions & 0 deletions logging/zap/logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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()
}

0 comments on commit ebef6a5

Please sign in to comment.