rs / zerolog

Zero Allocation JSON Logger
MIT License
10.39k stars 566 forks source link

Confused about usage of Ctx and Logger #609

Open kerak19 opened 10 months ago

kerak19 commented 10 months ago

Hi. One of main use cases I know for logger fields is to append more stuff as you go, but the return difference between Logger() and Ctx() makes it quite weird.

Let's say we have this code snippet:

log := zerolog.Ctx(ctx)

objectWithID := dependency.GetObjectWithID()

log = log.With().Str("object_id", objectWithID).Logger()

The snippet above won't work, because Ctx() returns *Logger while Logger() returns Logger (non-pointer). In order for it to work we need to modify the snippet to:

log := *zerolog.Ctx(r.Context())

objectWithID := dependency.GetObjectWithID()

log = log.With().Str("object_id", objectWithID).Logger()

or

log := zerolog.Ctx(r.Context()).With().Logger()

objectWithID := dependency.GetObjectWithID()

log = log.With().Str("object_id", objectWithID).Logger()

which doesn't look ideal.

Am I missing something or perhaps this use case is too obscure?

vdaviot commented 8 months ago

Hi!

We've also stumbled on the same problem and are looking forward to discussing potential solutions 👍

It just doesn't feel right.

peter-crist commented 4 months ago

It would be nice if Go allowed for you to take the address within a single line like:

log = &log.With().Str("request_id", requestID).Logger()

But unfortunately stuck with a workaround like this for now:

log = toPointer(log.With().Str("request_id", requestID).Logger())
...
func toPointer(l zerolog.Logger) *zerolog.Logger {
   return &l
}
freepaddler commented 2 days ago

I faced the same confusion, but now its cleared.

I think the reason is described in FAQ

that's why your following example is wrong

log := zerolog.Ctx(r.Context()).With().Logger()

objectWithID := dependency.GetObjectWithID()

log = log.With().Str("object_id", objectWithID).Logger()

In this case log is not the same logger, that you've got from context. If you try to log.UpdateContext(...) your logger in r.Context() wouldn't change.

So I guess, that pointer here defines shared Logger vs local instance.