Skip to content

Commit 995de2a

Browse files
authored
logging/zap/ctxzap: add caller skip to shorthand functions (#429)
The caller annotations made by the shorthand logging functions are `ctxzap/context.go:xx` regardless of where the shorthands are called. This commit adds caller skip so that each log message has the correct caller annotation.
1 parent a63f4c4 commit 995de2a

File tree

2 files changed

+9
-5
lines changed

2 files changed

+9
-5
lines changed

logging/zap/ctxzap/context.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -66,23 +66,23 @@ func ToContext(ctx context.Context, logger *zap.Logger) context.Context {
6666
// Debug is equivalent to calling Debug on the zap.Logger in the context.
6767
// It is a no-op if the context does not contain a zap.Logger.
6868
func Debug(ctx context.Context, msg string, fields ...zap.Field) {
69-
Extract(ctx).Debug(msg, fields...)
69+
Extract(ctx).WithOptions(zap.AddCallerSkip(1)).Debug(msg, fields...)
7070
}
7171

7272
// Info is equivalent to calling Info on the zap.Logger in the context.
7373
// It is a no-op if the context does not contain a zap.Logger.
7474
func Info(ctx context.Context, msg string, fields ...zap.Field) {
75-
Extract(ctx).Info(msg, fields...)
75+
Extract(ctx).WithOptions(zap.AddCallerSkip(1)).Info(msg, fields...)
7676
}
7777

7878
// Warn is equivalent to calling Warn on the zap.Logger in the context.
7979
// It is a no-op if the context does not contain a zap.Logger.
8080
func Warn(ctx context.Context, msg string, fields ...zap.Field) {
81-
Extract(ctx).Warn(msg, fields...)
81+
Extract(ctx).WithOptions(zap.AddCallerSkip(1)).Warn(msg, fields...)
8282
}
8383

8484
// Error is equivalent to calling Error on the zap.Logger in the context.
8585
// It is a no-op if the context does not contain a zap.Logger.
8686
func Error(ctx context.Context, msg string, fields ...zap.Field) {
87-
Extract(ctx).Error(msg, fields...)
87+
Extract(ctx).WithOptions(zap.AddCallerSkip(1)).Error(msg, fields...)
8888
}

logging/zap/ctxzap/context_test.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package ctxzap
22

33
import (
44
"context"
5+
"runtime"
56
"testing"
67

78
"go.uber.org/zap"
@@ -31,8 +32,11 @@ func TestShorthands(t *testing.T) {
3132
if e.Message != message {
3233
t.Fatalf("message: expected %v, got %v", message, e.Message)
3334
}
35+
if _, file, _, _ := runtime.Caller(0); e.Caller.File != file {
36+
t.Errorf("caller: expected %v, got %v", file, e.Caller.File)
37+
}
3438
return nil
35-
})))
39+
}))).WithOptions(zap.AddCaller())
3640
ctx := ToContext(context.Background(), logger)
3741
c.fn(ctx, message)
3842
if !called {

0 commit comments

Comments
 (0)