rs / zerolog

Zero Allocation JSON Logger
MIT License
10.41k stars 567 forks source link

log error type #448

Open roccoblues opened 2 years ago

roccoblues commented 2 years ago

Hi,

is it possible to log the error type in addition to the string? And if not would you be open for a PR that adds the functionality?

The background is that Datadog has some standard attributes that enable an enhanced UI view, for example grouping by error kind.

Currently we set:

zerolog.ErrorFieldName = "error.message"

It would be great to have an (opt-in) feature like:

zerolog.LogErrorType=true
zerolog.ErrorTypeFieldName = "error.kind" // populated with fmt.Sprintf("%T", err)
devcorpio commented 1 year ago

It's true that it's possible to add the "error.kind" attribute manually executing:

log.Err(err).Str("error.kind", "my-favourite-kind").Msg("log error")

Nevertheless, it would be also nice to rely on "MarshalZerologObject" to add custom attributes to the error log.

Basic example:

type MyError struct {
    Message string
        Kind string

}

func (e UsageError) Error() string {
    return e.Message
}

func (me MyError) MarshalZerologObject(e *zerolog.Event) {
    e.Str("error.kind", me.Kind)
}

Unfortunately, the MarshalZerologObject only adds keys within zerolog.ErrorFieldName and not at the "top" level. Example:

err: = MyError{ Message: "my-error-message", Kind: "my-favourite-kind" }
log.Err(err).Str(Msg("log error")

Current output:

{"log.level":"error","error.message":{"error.kind":"my-favourite-kind"}, "message":"log error"}

Wished output:

{"log.level":"error","error.message": "my-error-message", "error.kind": "my-favourite-kind", "message":"log error"}

As far as I understand, the only way to achieve what I want is adding manually the attribute when calling Log.Err(err). Is that right?

@roccoblues, did you find a way to do what you asked for?

roccoblues commented 1 year ago

@devcorpio sorry no, we're also adding the error.kind manually.

devcorpio commented 1 year ago

thank you for your answer, @roccoblues