Attributes Extracted from Context Workflow
mainThis workflow allows you to use standard slog methods (like slog.InfoContext) while automatically injecting attributes from the context.Context into the log lines. This is ideal when you are using the default package-level logger but passing a context around.
Append and Prepend
Use slogctx.Prepend(ctx, ...) to add attributes to the start of log lines, or slogctx.Append(ctx, ...) to add them to the end. Both accept a mix of slog.Attr and key-value pairs.
Custom Context Value Extractor
You can define custom logic to extract values from a context using the AttrExtractor type. Register these in slogctx.HandlerOptions under Prependers or Appenders.
OpenTelemetry TraceID/SpanID Extractor
To include OTEL tracing information, install the sub-module:
go get github.com/veqryn/slog-context/otel
Then use slogotel.ExtractTraceSpanID in your HandlerOptions.
HTTP Middleware and Extractor
For web servers, use the sloghttp package. The sloghttp.AttrCollection middleware allows you to collect attributes (like request IDs) that will be available to all log calls within that request's context.
// Example: Custom Extractor
type ctxKey struct{}
func customExtractor(ctx context.Context, _ time.Time, _ slog.Level, _ string) []slog.Attr {
if v, ok := ctx.Value(ctxKey{}).(string); ok {
return []slog.Attr{slog.String("my-key", v)}
}
return nil
}
func main() {
h := slogctx.NewHandler(
slog.NewJSONHandler(os.Stdout, nil),
&slogctx.HandlerOptions{
Prependers: []slogctx.AttrExtractor{slogctx.ExtractPrepended},
Appenders: []slogctx.AttrExtractor{
slogctx.ExtractAppended,
customExtractor,
},
},
)
slog.SetDefault(slog.New(h))
}