Skip to content

Commit

Permalink
logging/zap/ctxzap: add caller skip to shorthand functions (#429)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
jkawamoto authored Jun 19, 2021
1 parent a63f4c4 commit 995de2a
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 5 deletions.
8 changes: 4 additions & 4 deletions logging/zap/ctxzap/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,23 +66,23 @@ func ToContext(ctx context.Context, logger *zap.Logger) context.Context {
// Debug is equivalent to calling Debug on the zap.Logger in the context.
// It is a no-op if the context does not contain a zap.Logger.
func Debug(ctx context.Context, msg string, fields ...zap.Field) {
Extract(ctx).Debug(msg, fields...)
Extract(ctx).WithOptions(zap.AddCallerSkip(1)).Debug(msg, fields...)
}

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

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

// Error is equivalent to calling Error on the zap.Logger in the context.
// It is a no-op if the context does not contain a zap.Logger.
func Error(ctx context.Context, msg string, fields ...zap.Field) {
Extract(ctx).Error(msg, fields...)
Extract(ctx).WithOptions(zap.AddCallerSkip(1)).Error(msg, fields...)
}
6 changes: 5 additions & 1 deletion logging/zap/ctxzap/context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package ctxzap

import (
"context"
"runtime"
"testing"

"go.uber.org/zap"
Expand Down Expand Up @@ -31,8 +32,11 @@ func TestShorthands(t *testing.T) {
if e.Message != message {
t.Fatalf("message: expected %v, got %v", message, e.Message)
}
if _, file, _, _ := runtime.Caller(0); e.Caller.File != file {
t.Errorf("caller: expected %v, got %v", file, e.Caller.File)
}
return nil
})))
}))).WithOptions(zap.AddCaller())
ctx := ToContext(context.Background(), logger)
c.fn(ctx, message)
if !called {
Expand Down

0 comments on commit 995de2a

Please sign in to comment.