Skip to content

Commit 27ca785

Browse files
authored
v2:providers/zap: fix caller annotation (#432)
`Logger.Log` calls a zap's log function inside of this function. As a result, caller annotations always point `logger.go`. This commit adds caller skip so that each log message has the correct annotation.
1 parent 0c113ab commit 27ca785

File tree

2 files changed

+40
-4
lines changed

2 files changed

+40
-4
lines changed

providers/zap/logger.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,13 +25,13 @@ func InterceptorLogger(logger *zap.Logger) *Logger {
2525
func (l *Logger) Log(lvl logging.Level, msg string) {
2626
switch lvl {
2727
case logging.DEBUG:
28-
l.Debug(msg)
28+
l.WithOptions(zap.AddCallerSkip(1)).Debug(msg)
2929
case logging.INFO:
30-
l.Info(msg)
30+
l.WithOptions(zap.AddCallerSkip(1)).Info(msg)
3131
case logging.WARNING:
32-
l.Warn(msg)
32+
l.WithOptions(zap.AddCallerSkip(1)).Warn(msg)
3333
case logging.ERROR:
34-
l.Error(msg)
34+
l.WithOptions(zap.AddCallerSkip(1)).Error(msg)
3535
default:
3636
panic(fmt.Sprintf("zap: unknown level %s", lvl))
3737
}

providers/zap/logger_test.go

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package zap
2+
3+
import (
4+
"runtime"
5+
"testing"
6+
7+
"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/logging"
8+
"go.uber.org/zap"
9+
"go.uber.org/zap/zapcore"
10+
"go.uber.org/zap/zaptest"
11+
)
12+
13+
func TestLogger_Log(t *testing.T) {
14+
msg := "message"
15+
16+
levels := []logging.Level{logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR}
17+
for _, level := range levels {
18+
called := false
19+
logger := InterceptorLogger(zaptest.NewLogger(t, zaptest.WrapOptions(zap.Hooks(func(entry zapcore.Entry) error {
20+
called = true
21+
22+
if entry.Message != msg {
23+
t.Errorf("expect %v, got %v", msg, entry.Message)
24+
}
25+
if _, file, _, _ := runtime.Caller(0); entry.Caller.File != file {
26+
t.Errorf("caller: expected %v, got %v", file, entry.Caller.File)
27+
}
28+
return nil
29+
}), zap.AddCaller())))
30+
31+
logger.Log(level, msg)
32+
if !called {
33+
t.Error("hook isn't called")
34+
}
35+
}
36+
}

0 commit comments

Comments
 (0)