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

Allow user configuration of default logger to return from Ctx() #343

Merged
merged 1 commit into from Aug 12, 2021
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 4 additions & 1 deletion ctx.go
Expand Up @@ -39,10 +39,13 @@ func (l *Logger) WithContext(ctx context.Context) context.Context {
}

// Ctx returns the Logger associated with the ctx. If no logger
// is associated, a disabled logger is returned.
// is associated, DefaultContextLogger is returned, unless DefaultContextLogger
// is nil, in which case a disabled logger is returned.
func Ctx(ctx context.Context) *Logger {
if l, ok := ctx.Value(ctxKey{}).(*Logger); ok {
return l
} else if l = DefaultContextLogger; l != nil {
return l
}
return disabledLogger
}
7 changes: 7 additions & 0 deletions ctx_test.go
Expand Up @@ -27,6 +27,13 @@ func TestCtx(t *testing.T) {
if log2 != disabledLogger {
t.Error("Ctx did not return the expected logger")
}

DefaultContextLogger = &log
t.Cleanup(func() { DefaultContextLogger = nil })
log2 = Ctx(context.Background())
if log2 != &log {
t.Error("Ctx did not return the expected logger")
}
}

func TestCtxDisabled(t *testing.T) {
Expand Down
4 changes: 4 additions & 0 deletions globals.go
Expand Up @@ -100,6 +100,10 @@ var (
// output. If not set, an error is printed on the stderr. This handler must
// be thread safe and non-blocking.
ErrorHandler func(err error)

// DefaultContextLogger is returned from Ctx() if there is no logger associated
// with the context.
DefaultContextLogger *Logger
)

var (
Expand Down