Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

AddCallerSkip in RedirectStdLog (#320) #321

Merged
merged 3 commits into from
Feb 19, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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.")
})
}