Documentation
¶
Overview ¶
Package errcontext attaches structured logging context to errors. It wraps errors with a Context map using xerrors.Extend, enabling downstream callers to extract slog.Attr key-value pairs for logging.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Add ¶
Add attaches the given slog.Attr key-value pairs to err as logging context. If err already has a Context, the existing map is mutated in place (last-entry-wins). Returns nil if err is nil, or err unchanged if no attrs are provided.
Example ¶
package main
import (
"errors"
"log/slog"
"os"
"github.com/wood-jp/xerrors"
"github.com/wood-jp/xerrors/errcontext"
)
func newLogger() *slog.Logger {
return slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey && len(groups) == 0 {
return slog.Attr{}
}
return a
},
}))
}
func main() {
err := errors.New("request failed")
err = errcontext.Add(err,
slog.String("user_id", "u123"),
slog.Int("status", 503),
)
newLogger().Error("handler error", xerrors.Log(err))
}
Output: {"level":"ERROR","msg":"handler error","error":{"error":"request failed","error_detail":{"context":{"status":503,"user_id":"u123"}}}}
Types ¶
Click to show internal directories.
Click to hide internal directories.