rs / zerolog

Zero Allocation JSON Logger
MIT License
10.61k stars 572 forks source link

How do I create a standard zerolog.Event I can use as a middleware? #581

Open renatospaka opened 1 year ago

renatospaka commented 1 year ago

Hello folks.

I have overwritten some of the events zerolog provides to improve my design. However, my code has become heavily duplicated and I want to reduce this duplication.

func (l *Logger) Error(msg string) {
    l.logg.Error().
        Str("appName", strings.ToUpper(l.App)).
        Str("environment", l.config.Environment).
        Str("method", l.methodOrService.method).
        Str("step", l.methodOrService.step).
        Str("transactionId", l.methodOrService.transactionId).
        Str("clientId", l.methodOrService.clientId).
        Str("frontDoor", l.methodOrService.frontDoor).
        Str("transactiionStatusOutput", l.methodOrService.transactiionStatusOutput).
        Msg(msg)
}
func (l *Logger) Panic(msg string) {
    l.logg.Panic().
        Str("appName", strings.ToUpper(l.App)).
        Str("environment", l.config.Environment).
        Str("method", l.methodOrService.method).
        Str("step", l.methodOrService.step).
        Str("transactionId", l.methodOrService.transactionId).
        Str("clientId", l.methodOrService.clientId).
        Str("frontDoor", l.methodOrService.frontDoor).
        Str("transactiionStatusOutput", l.methodOrService.transactiionStatusOutput).
        Msg(msg)
}

These methods above repeat to Warn(), Info(), Error(), Debug().

The main goal is to reduce coder effort. But my code turned into spaghetti and I need directions to refactor it, creating a kind of "middleware" to encapsulate it:

Str("appName", strings.ToUpper(l.App)).
Str("environment", l.config.Environment).
Str("method", l.methodOrService.method).
Str("step", l.methodOrService.step).
Str("transactionId", l.methodOrService.transactionId).
Str("clientId", l.methodOrService.clientId).
Str("frontDoor", l.methodOrService.frontDoor).
Str("transactiionStatusOutput", l.methodOrService.transactiionStatusOutput).

So I created an zerolog.Event with all those Str but it completely failed on implementation.

Now I am open to suggestions.