slogerr provides Error and NamedError helpers for Go's log/slog package, inspired by the equivalent functions in uber-go/zap.
Each helper returns a slog.Attr that encodes structured error information:
msg— the error message fromerr.Error()verbose— the%+vrepresentation, added only when it differs frommsg(e.g. errors carrying a stack trace)causes— the individual errors whenerrwraps multiple errors viaerrors.Joinorfmt.Errorf("%w %w", ...)
go get github.com/utgwkk/slogerr
import (
"errors"
"log/slog"
"github.com/utgwkk/slogerr"
)
// Basic usage — key is "error"
slog.Info("request failed", slogerr.Error(err))
// Custom key
slog.Info("request failed", slogerr.NamedError("cause", err))
// nil is a no-op: returns a zero-value slog.Attr that handlers skip
slog.Info("maybe failed", slogerr.Error(nil))
// errors.Join: individual causes are recorded under "causes"
joined := errors.Join(errors.New("db error"), errors.New("timeout"))
slog.Info("multiple errors", slogerr.Error(joined))The attribute value is a slog.GroupValue, so with slog.NewJSONHandler the output looks like:
Simple error
{"msg":"request failed","error":{"msg":"something went wrong"}}Error with verbose representation (e.g. from github.com/pkg/errors)
{"msg":"request failed","error":{"msg":"something went wrong","verbose":"something went wrong\nmain.main()\n\t/app/main.go:42"}}Joined errors
{"msg":"request failed","error":{"msg":"db error\ntimeout","causes":{"0":{"msg":"db error"},"1":{"msg":"timeout"}}}}Note:
slog's type system has no native array kind; causes are represented as a group with numeric string keys ("0","1", ...) rather than a JSON array.
This library is inspired by the Error and NamedError functions in
uber-go/zap (MIT License, Copyright (c) 2016–2024 Uber Technologies, Inc.).