Skip to content

Commit

Permalink
Increase caller skip when hijacking stdlib's logging (#321)
Browse files Browse the repository at this point in the history
When hijacking the standard library's "log" package, increment the logger's caller skip so that caller annotations are correct.

Fixes #320.
  • Loading branch information
skipor authored and akshayjshah committed Feb 19, 2017
1 parent ae20ebc commit 5e71114
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
8 changes: 7 additions & 1 deletion global.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,17 @@ func ReplaceGlobals(logger *Logger) func() {
// It returns a function to restore the original prefix and flags and reset the
// standard library's output to os.Stdout.
func RedirectStdLog(l *Logger) func() {
const (
stdLogDefaultDepth = 4
loggerWriterDepth = 1
)
flags := log.Flags()
prefix := log.Prefix()
log.SetFlags(0)
log.SetPrefix("")
log.SetOutput(&loggerWriter{l})
log.SetOutput(&loggerWriter{l.WithOptions(
AddCallerSkip(stdLogDefaultDepth + loggerWriterDepth),
)})
return func() {
log.SetFlags(flags)
log.SetPrefix(prefix)
Expand Down
11 changes: 11 additions & 0 deletions global_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

"go.uber.org/zap/internal/observer"
"go.uber.org/zap/zapcore"
Expand Down Expand Up @@ -76,3 +77,13 @@ func TestRedirectStdLog(t *testing.T) {
assert.Equal(t, initialFlags, log.Flags(), "Expected to reset initial flags.")
assert.Equal(t, initialPrefix, log.Prefix(), "Expected to reset initial prefix.")
}

func TestRedirectStdLogCaller(t *testing.T) {
withLogger(t, DebugLevel, []Option{AddCaller()}, func(l *Logger, logs *observer.ObservedLogs) {
defer RedirectStdLog(l)()
log.Print("redirected")
entries := logs.All()
require.Len(t, entries, 1, "Unexpected number of logs.")
assert.Contains(t, entries[0].Entry.Caller.File, "global_test.go", "Unexpected caller annotation.")
})
}

0 comments on commit 5e71114

Please sign in to comment.