I'm using zerolog
in a Go application and trying to log errors. However, when I call .Err()
on the logger, the error
field doesn’t show up in the console output. Everything else logs correctly except the error itself.
Here’s how I set up the logger:
var (
once sync.Once
log zerolog.Logger
)
func Get() zerolog.Logger {
once.Do(func() {
zerolog.ErrorStackMarshaler = pkgerrors.MarshalStack
zerolog.TimeFieldFormat = time.RFC3339Nano
var output io.Writer = zerolog.ConsoleWriter{
Out: os.Stdout,
TimeFormat: time.RFC3339,
FieldsExclude: []string{
"user_agent",
"git_revision",
"go_version",
},
}
var gitRevision string
buildInfo, ok := debug.ReadBuildInfo()
if ok {
for _, v := range buildInfo.Settings {
if v.Key == "vcs.revision" {
gitRevision = v.Value
break
}
}
}
logLevel := int(zerolog.InfoLevel)
log = zerolog.New(output).
Level(zerolog.Level(logLevel)).
With().
Stack().
Caller().
Timestamp().
Str("git_revision", gitRevision).
Str("go_version", buildInfo.GoVersion).
Logger()
zerolog.DefaultContextLogger = &log
})
return log
}
Then, in a route handler, I use the logger like this:
l = logger.Get()
reqIDRaw := middleware.GetReqID(r.Context())
l.Warn().
Str("requestID", reqIDRaw).
Str("method", r.Method).
Str("url", r.URL.Path).
Err(errors.Wrap(err, "bad request")).
Msg("bad request")
2025-02-24T10:02:35+03:00 WRN internal/services/response/error_response.go:43 > bad request method=POST requestID=Kengos-MacBook-Pro.local/0hS9QB33oG-000001 url=/v1/auth/register
The error
field is completely missing from the output, even though I passed it with .Err()
.
I’ve tried adding FormatFieldName
to the ConsoleWriter
, but it still doesn’t show:
FormatFieldName: func(field string) string {
if field == "error" {
return field
}
return field
},
I also tried using FormatFieldValue
, but no luck.
I’d like the log output to include the error, like this:
error=bad request: some detailed error message
What am I missing? How do I make zerolog
actually show the error field in console output?