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

Confused about usage of Ctx and Logger #609

Open
kerak19 opened this issue Oct 24, 2023 · 3 comments
Open

Confused about usage of Ctx and Logger #609

kerak19 opened this issue Oct 24, 2023 · 3 comments

Comments

@kerak19
Copy link

kerak19 commented Oct 24, 2023

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
Copy link

vdaviot commented Jan 10, 2024

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
Copy link

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
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants