diff --git a/README.md b/README.md index f7ff10f4..3d09f14c 100644 --- a/README.md +++ b/README.md @@ -400,6 +400,29 @@ log.Ctx(ctx).Info().Msg("hello world") // Output: {"component":"module","level":"info","message":"hello world"} ``` +### Use default logger from context + +If one try to get logger from context that has not logger within it the default, disabled logger will be returned +```go +ctx := context.Background() + +log.Ctx(ctx).Info().Msg("hello world") + +// No output by default! +``` +You can easily substitute default logger with your own instance +```go +logger := log.With().Str("component", "module").Logger() + +zerolog.DefaultLogger = &logger + +ctx := context.Background() + +log.Ctx(ctx).Info().Msg("hello world") + +// Output: {"component": "module", "level": "info", "message": "hello world"} +``` + ### Set as standard logger output ```go diff --git a/ctx.go b/ctx.go index 2b7a6823..2f559dfb 100644 --- a/ctx.go +++ b/ctx.go @@ -4,11 +4,14 @@ import ( "context" ) -var disabledLogger *Logger +// DefaultLogger is used if user tries to get Logger from context.Context that has not Logger within it +// By default it is disabled, meaning it logs nothing at all, +// but it can be easily substituted by custom instance with different behavior. +var DefaultLogger *Logger func init() { l := Nop() - disabledLogger = &l + DefaultLogger = &l } type ctxKey struct{} @@ -43,5 +46,5 @@ func Ctx(ctx context.Context) *Logger { if l, ok := ctx.Value(ctxKey{}).(*Logger); ok { return l } - return disabledLogger + return DefaultLogger } diff --git a/ctx_test.go b/ctx_test.go index 646cd0fb..a9007b49 100644 --- a/ctx_test.go +++ b/ctx_test.go @@ -24,7 +24,7 @@ func TestCtx(t *testing.T) { } log2 = Ctx(context.Background()) - if log2 != disabledLogger { + if log2 != DefaultLogger || log2.level != Disabled { t.Error("Ctx did not return the expected logger") } } @@ -58,6 +58,14 @@ func TestCtxDisabled(t *testing.T) { ctx = dl.WithContext(ctx) if Ctx(ctx) != &dl { - t.Error("WithContext did not overide logger with a disabled logger") + t.Error("WithContext did not override logger with a disabled logger") + } +} + +func TestCtxCustomDefault(t *testing.T) { + logger := New(ioutil.Discard).With().Str("custom_field", "custom_value").Logger() + DefaultLogger = &logger + if Ctx(context.Background()) != &logger { + t.Error("default logger has not been substituted") } } diff --git a/log.go b/log.go index da64b8a3..7be322c4 100644 --- a/log.go +++ b/log.go @@ -235,7 +235,7 @@ func (l Logger) With() Context { // // Use this method with caution. If unsure, prefer the With method. func (l *Logger) UpdateContext(update func(c Context) Context) { - if l == disabledLogger { + if l == DefaultLogger { return } if cap(l.context) == 0 {