coder / slog

Minimal structured logging library for Go

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Implement api to accept empty error

Emyrk opened this issue · 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.

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

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.

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.

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