ZeroLog runtime error

I have a project that using concurrent goroutines and each process log messages
I am seeing below random exception, either for
log.Msgf or log event

panic: runtime error: index out of range [-1]

goroutine 6190 [running]:
github.com/rs/zerolog/internal/json.Encoder.AppendKey(...)
/vendor/github.com/rs/zerolog/internal/json/base.go:15
github.com/rs/zerolog.(*Event).Str(0xc003e10ba0?, {0x11a06c2?, 0xc000470ee0?}, {0x0?, 0x1e?})
/vendor/github.com/rs/zerolog/event.go:247 +0x13d

Can you show your code? I found a similar error message in an issue here: panic: runtime error: index out of range [-1] seen when logging with many go coroutines running · Issue #422 · rs/zerolog · GitHub

here is short version of the code

main.go.
log.Info().Msgf(“%v”, clientName) – to write messages about initializing programs/clients

api request starts a few goroutines – each routine has following

  • log.Debug() or log.Msgf()
  • defer func(start time.Time) {
    var e *zerolog.Event
    switch {
    case err != nil:
    e = log.Error()
    default:
    e = log.WithLevel(v.Config.Level())
    }
    e.
    Str(“message”, message).
    e.AnErr(constants.Err, err).Send()
    }(time.Now())

sean – any update on this issue ?
I have reviewed the code couple of times, do not see log event being reused between goroutines.

Your code formatting above makes it slightly hard to read. If you can create a reproducible example in the go playground, you could try opening an issue in the github repo of the library you’re trying to use.

I checked the ZeroLog source. It has a single global json formatter and does not synchronize access to the formatter. Multiple goroutines calling ZeroLog functions that require the json formatter can cause the json formatter’s state to become corrupt.

thank Dean and Jeff.
So the only solution, is to initialize logger within each goroutine

That won’t help because the ZeroLog json formatter is global. If you must log in json, then you need to protect your logging calls with a mutex.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.