zerolog icon indicating copy to clipboard operation
zerolog copied to clipboard

Context's Logger() method returning a non-pointer

Open nickcorin opened this issue 3 years ago • 1 comments

As per the documentation for zerolog, using contexts to pass sub-loggers should work something like this:

ctx := log.With().Str("component", "module").Logger().WithContext(ctx)

log.Ctx(ctx).Info().Msg("hello world")

// Output: {"component":"module","level":"info","message":"hello world"}

This doesn't work, however, since the Logger() method on Context returns a non-pointer and WithContext(context.Context) requires a pointer receiver.

I have had to use a workaround that looks like this:

ctxLogger := log.With().Str("component", "module").Logger()
ctx := (&ctxLogger).WithContext(ctx)

log.Ctx(ctx).Info().Msg("hello world")

// Output: {"component":"module","level":"info","message":"hello world"}

It works, but is not pretty.

Were there any major design considerations for using a non-pointer receiver for Logger()?

I'm more than happy to create the PR to change this if you agree that it's a good idea.

nickcorin avatar Jan 24 '22 08:01 nickcorin

This issue is the same as #116, just with a different proposed solution.

smyrman avatar Feb 02 '22 09:02 smyrman

This has been fixed with #409 and #499 by changing WithContext to not be pointer receiver and keeping Logger to be value receiver. I think this could be closed unless we want to discuss making all methods be of the same receiver type (also opened in #563).

mitar avatar Aug 18 '23 12:08 mitar