slog icon indicating copy to clipboard operation
slog copied to clipboard

Implement api to accept empty error

Open Emyrk opened this issue 5 years ago • 4 comments

Zerolog has this nifty api log.Err(err error) that is Error level if err != nil and Info level if err == nil

The basic gist to avoid this common code:

authenticated, err := auth()
if err != nil {
  slog.Error(ctx, "failed to authorize user"
    slog.Error(err),
    slog.F("user", "alice")
  )
  return
}

slog.Info(ctx, "authorized user",
    slog.F("user", "alice"),
)
...

and you can just do (the message becomes the action, and the Error level indicates the action failed):

authenticated, err := auth()
// Unsure exactly on the API, still adapting to slog, so unsure what would be "natural" 
slog.Err(err).(ctx, "authorize user", 
  slog.F("user", "alice")
)

if err != nil {
  return
}
...

It is a small feature I miss. Let me know what you think.

Emyrk avatar Jan 22 '21 20:01 Emyrk

This is interesting but it seems very similar to using throw/catch versus Go's indented error paths idiom.

nhooyr avatar Jan 25 '21 18:01 nhooyr

This is interesting but it seems very similar to using throw/catch versus Go's indented error paths idiom.

I can see what you mean, but it does not affect how to logically handle the error, just how to log it.

Emyrk avatar Jan 25 '21 19:01 Emyrk

I can see what you mean, but it does not affect how to logically handle the error, just how to log it.

Let me just say first that I fully agree Go takes the whole indent every error path thing way too far and it gets very repetitive. But slog aims to follow Go idioms. And handling an error is no different than logging it.

I wouldn't stop such a change though if the Go team @cdr was in majority support.

nhooyr avatar Jan 25 '21 19:01 nhooyr

Or sorry not no different, I meant logging is part of handling an error.

nhooyr avatar Jan 25 '21 19:01 nhooyr