zerolog icon indicating copy to clipboard operation
zerolog copied to clipboard

log error type

Open roccoblues opened this issue 3 years ago • 3 comments

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)

roccoblues avatar Jun 29 '22 18:06 roccoblues

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?

devcorpio avatar May 30 '23 12:05 devcorpio

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

roccoblues avatar May 30 '23 19:05 roccoblues

thank you for your answer, @roccoblues

devcorpio avatar Jun 01 '23 09:06 devcorpio