How to replace using zap logger .With() instead of append

194 Views Asked by At

I want to add shared fields to the logger so that subsequent logs will all contain some common fields.

There are the options to use (*zap.Logger) With() or (*zap.Logger) WithOptions(zap.Fields). However both append fields instead of replace.

I had logs that had repeated field values, probably because I called With() at multiple places for the same logger instance. i.e.

func fnA(ctx context.Context) {
    zaplogger := FromContext(ctx)
    zaplogger = zaplogger.With(zap.String("a", "123"))
    ctx = NewContext(ctx, zaplogger)
    ...

    fnB(ctx)
}

func fnB(ctx context.Context) {
    zaplogger := FromContext(ctx)
    zaplogger = zaplogger.With(zap.String("a", "123"))
    // log becomes {"a": "123123"}
}

Is there a way to do a replace instead of append or check for existing field?

0

There are 0 best solutions below