Documentation
¶
Overview ¶
Package logger builds the service's *slog.Logger: a JSON handler chain that correlates every record with the active trace, tags it with the service identity, and can fire side-effect hooks per level.
New and NewWithHandler return a plain *slog.Logger, so the same logger is used everywhere — HTTP/gRPC handlers, business code, background workers and SDK packages — and third-party code logs through the same handler. BuildInfo logs the binary's embedded VCS/build metadata at startup.
Usage ¶
Build one logger at startup and inject it:
log := logger.New(os.Stdout, logger.Config{
Service: "myapp", // service.name
Version: version, // service.version — the build version
Level: logger.LevelInfo,
AddSource: true,
})
log.InfoContext(ctx, "service started", "addr", ":8080")
access := log.With("logger", "access") // child tagged logger=access
access.InfoContext(ctx, "request", "method", "GET", "path", "/")
Always log with a context (InfoContext, ErrorContext, ...; the sloglint linter enforces it): the context carries cancellation and the span the record is correlated with.
Correlation and identity ¶
When the context carries a valid OpenTelemetry span context, every record gets trace_id, span_id and trace_flags at its top level — outside any WithGroup — so a collector can link the line to its trace. Without one the fields are omitted. Config.Service and Config.Version are written as service.name and service.version, the OpenTelemetry resource attribute names; an empty Version is omitted.
Multiple sinks ¶
To split output by level, combine handlers with slog.NewMultiHandler and pass it to NewWithHandler. Each wrapped handler's own Enabled check gates which records it receives:
stdout := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: logger.LevelInfo})
h := slog.NewMultiHandler(stdout, sentryHandler) // sentryHandler.Enabled gates ERROR+
log := logger.NewWithHandler(h, logger.Config{Service: "myapp", Version: version})
Side-effect hooks (Events) ¶
Events attaches a per-level callback that fires IN ADDITION to normal handling — the record is still written to every sink. Use it for side effects like alerting or Sentry capture on ERROR, without disturbing stdout logging:
log := logger.New(os.Stdout, logger.Config{
Service: "myapp",
Level: logger.LevelInfo,
Events: logger.Events{
Error: func(ctx context.Context, r slog.Record) {
alert.Capture(ctx, r) // r carries service.*, trace fields and With attrs
},
},
})
The callback receives the full slog.Record with the accumulated With and service.* attributes and the trace fields replayed in, so it sees the same context the sink writes. It runs synchronously before the write, so keep it fast (offload slow work to a goroutine) and do not log at the same level from within it (that re-enters the hook).
Events is a hook, not a router: it is additive to whatever sink you built. To send full records to several destinations by level, use slog.NewMultiHandler (above); the two combine — a multi-handler sink plus an Error hook.
Conventions ¶
- Errors go under the key "err" with an error value: log.ErrorContext(ctx, "save failed", "err", err).
- A recovered panic is logged with PanicArgs: err plus exception.stacktrace.
- Custom levels stay within [-8, 15], the range OpenTelemetry severity numbers map to.
Config ¶
Config fields:
- Service: written as "service.name" on every record.
- Version: written as "service.version"; empty omits it.
- Level: minimum level handled (LevelDebug/LevelInfo/LevelWarn/LevelError).
- AddSource: attach a "source" attribute shortened to file:line.
- Events: optional per-level side-effect hook (see above); zero = none.
New applies Level and AddSource to its JSON handler; NewWithHandler leaves both to the handler it is given.
Index ¶
Constants ¶
const ( LevelDebug = slog.LevelDebug LevelInfo = slog.LevelInfo LevelWarn = slog.LevelWarn LevelError = slog.LevelError )
Log levels, re-exported from slog for convenience.
Variables ¶
This section is empty.
Functions ¶
func BuildInfo ¶ added in v0.14.0
BuildInfo logs the build metadata embedded in the Go binary (VCS revision, dirty flag, build settings, Go and module versions) at info level. Call it once at startup so every process records exactly what is running. When the info is unavailable (e.g. `go run` without VCS stamping) it logs a warning instead.
func New ¶
New builds a logger writing JSON to w. For several sinks, build the logger with NewWithHandler over slog.NewMultiHandler instead. A logger over io.Discard drops every record before it is built and fires no Events hook.
func NewWithHandler ¶
NewWithHandler builds a logger over a custom slog.Handler (e.g. one made by slog.NewMultiHandler). The service identity and Events from cfg are applied.
Everything is installed at the handler layer, so it applies to every logger derived with With/WithGroup and to third-party code logging through the same handler (e.g. httplog). The handler stack, innermost (closest to the sink) first, is:
h (the given sink)
└─ eventHandler (if cfg.Events is set: side-effect hooks, additive)
└─ WithAttrs(service.name, service.version)
└─ traceHandler (trace_id, span_id, trace_flags; see below)
traceHandler reads the span context from the ctx of each call and, when it is valid, adds trace_id, span_id and trace_flags at the top level of the record, outside any WithGroup. The event hook sits below service and trace so its callback sees the record with the full context it is written with.
func PanicArgs ¶ added in v0.14.0
PanicArgs returns the arguments a recovered panic p is logged with, followed by args: err, the error value "panic: <p>", and exception.stacktrace, the stack of the goroutine that recovered it. Call it in the deferred function:
if p := recover(); p != nil {
log.ErrorContext(ctx, "panic recovered", logger.PanicArgs(p, "path", r.URL.Path)...)
}
Types ¶
type Config ¶
type Config struct {
// Service tags every record with the service name (attribute
// "service.name").
Service string
// Version tags every record with the build version (attribute
// "service.version"); empty omits it.
Version string
// Level is the minimum level handled. New applies it; NewWithHandler
// leaves level filtering to the given handler.
Level Level
// AddSource attaches a "source" attribute (file:line) to records. New
// applies it; NewWithHandler leaves it to the given handler.
AddSource bool
// Events assigns an optional side-effect callback per level (e.g. fire an
// alert on Error). It is additive: the record is still written to the sink.
// Zero value installs no hook. See Events.
Events Events
}
Config configures the logger built by New or NewWithHandler.
type EventFn ¶ added in v0.6.0
EventFn is a side-effect callback invoked for a record at its level, IN ADDITION to normal handling — the record is still written to the underlying sink. Typical use: capture ERROR records to Sentry or fire an alert, while stdout logging is untouched.
Unlike a lossy decoded snapshot, the callback receives the full slog.Record, reconstructed to include the attributes accumulated via With and the service.* attributes (which live on the handler, not the record) plus trace_id, span_id and trace_flags, so the hook sees the same context the record is written with.
The callback runs synchronously on the logging goroutine, before the write. Keep it fast: offload slow work (network calls) to a goroutine or buffered channel. Do NOT log at the hooked level from inside the callback — that re-enters the hook and recurses.