zerolog: Context.Stack() not working
What happened:
Using Context.Stack().Logger() does not work, the stack is not added to each log entries.
What you expected to happen:
The stack field should be added to each log entries
How to reproduce it (as minimally and precisely as possible):
package main
import (
"github.com/pkg/errors"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/rs/zerolog/pkgerrors"
)
func myFunc() {
err := errors.New("my error")
err = errors.WithStack(errors.Wrap(err, "something failed"))
log.Error().Err(err).Msg("hello world")
}
func main() {
zerolog.ErrorStackMarshaler = pkgerrors.MarshalStack
log.Logger = log.With().Str("my", "field").Stack().Logger()
myFunc()
}
Anything else we need to know?:
I think it comes from the fact that Context.Stack() setup an Hook which is called after the event is completely built, so Err never see that Stack() was enabled.
We can see it because the following example works as expected:
package main
import (
"github.com/pkg/errors"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/rs/zerolog/pkgerrors"
)
func myFunc() {
err := errors.New("my error")
err = errors.WithStack(errors.Wrap(err, "something failed"))
log.Error().Stack().Err(err).Msg("hello world")
}
func main() {
zerolog.ErrorStackMarshaler = pkgerrors.MarshalStack
log.Logger = log.With().Str("my", "field").Logger()
myFunc()
}
I’m not sure how to fix this. One solution could be to add a stack field to Logger which would be transferred to the event in logger.newEvent.
About this issue
- Original URL
- State: closed
- Created 5 years ago
- Reactions: 3
- Comments: 19 (6 by maintainers)
I was expecting Stack hook should automatically enable Stack priniting but looks like I have to still call
logr.Error().Stack().Err(r.err).Msgf(format, args...)I also have this problem and created a PR a while back: https://github.com/rs/zerolog/pull/179
So my expectation from reading the docs is that by creating a logger with context by calling With().Stack().Logger() I should get a stacktrace when I call log.Err(errors.New(“testing 1 2 3”)) but that does not happen because when the hooks from the With().Stack() context aren’t processed until Msg() is called, which is after the Event.Err() function runs where it’s looking for e.stack to be true. Since the logger hook from the context has not been called yet, it’s always false. So the only way around it now is to call log.Error().Stack().Err(…) which is not what you necessarily want to do. For example, I only want to enable stacktrace output with errors when a user specifies a --debug flag, so I’d like to create a logger with Stack() context at runtime. I think if you can just update the logic of the Err() function in events.go, that should fix the issue.