Add slog logger with trace correlation
NewLogger builds a JSON/text slog logger with a runtime-adjustable level; TraceHandler adds trace_id and span_id from the context. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
022db31878
commit
598ee0536d
2 files changed
+242
No files matched your search
@@ -0,0 +1,129 @@
|
||||
package obsx
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
// Supported log formats for LogConfig.Format.
|
||||
const (
|
||||
FormatJSON = "json"
|
||||
FormatText = "text"
|
||||
)
|
||||
|
||||
// LogConfig configures the structured logger.
|
||||
type LogConfig struct {
|
||||
Level string // debug, info (default), warn, error; offsets like "debug-4" are accepted
|
||||
Format string // FormatJSON (default) or FormatText
|
||||
Output io.Writer // default: os.Stdout
|
||||
AddSource bool // include file:line of the log call
|
||||
}
|
||||
|
||||
func (c *LogConfig) defaults() {
|
||||
if c.Level == "" {
|
||||
c.Level = "info"
|
||||
}
|
||||
if c.Format == "" {
|
||||
c.Format = FormatJSON
|
||||
}
|
||||
if c.Output == nil {
|
||||
c.Output = os.Stdout
|
||||
}
|
||||
}
|
||||
|
||||
func (c LogConfig) validate() error {
|
||||
if _, err := ParseLevel(c.Level); err != nil {
|
||||
return err
|
||||
}
|
||||
switch strings.ToLower(c.Format) {
|
||||
case FormatJSON, FormatText:
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("obsx: unsupported log format %q (want %q or %q)", c.Format, FormatJSON, FormatText)
|
||||
}
|
||||
}
|
||||
|
||||
// NewLogger creates a slog.Logger that writes JSON (or text) records enriched
|
||||
// with trace_id and span_id from the context. The returned LevelVar allows
|
||||
// changing the level at runtime. An invalid level falls back to info.
|
||||
//
|
||||
// Use the *Context logging methods (InfoContext, ErrorContext, ...) to get
|
||||
// trace correlation.
|
||||
func NewLogger(cfg LogConfig) (*slog.Logger, *slog.LevelVar) {
|
||||
cfg.defaults()
|
||||
|
||||
lv := new(slog.LevelVar)
|
||||
if lvl, err := ParseLevel(cfg.Level); err == nil {
|
||||
lv.Set(lvl)
|
||||
}
|
||||
|
||||
opts := &slog.HandlerOptions{Level: lv, AddSource: cfg.AddSource}
|
||||
var h slog.Handler
|
||||
if strings.EqualFold(cfg.Format, FormatText) {
|
||||
h = slog.NewTextHandler(cfg.Output, opts)
|
||||
} else {
|
||||
h = slog.NewJSONHandler(cfg.Output, opts)
|
||||
}
|
||||
return slog.New(NewTraceHandler(h)), lv
|
||||
}
|
||||
|
||||
// ParseLevel parses a level name such as "debug", "INFO", "warn" or "error+2".
|
||||
func ParseLevel(s string) (slog.Level, error) {
|
||||
var l slog.Level
|
||||
if err := l.UnmarshalText([]byte(s)); err != nil {
|
||||
return 0, fmt.Errorf("obsx: invalid log level %q", s)
|
||||
}
|
||||
return l, nil
|
||||
}
|
||||
|
||||
// TraceHandler is a slog.Handler middleware that adds trace_id and span_id
|
||||
// attributes to every record logged with a context carrying a valid span.
|
||||
type TraceHandler struct {
|
||||
next slog.Handler
|
||||
}
|
||||
|
||||
// NewTraceHandler wraps h with trace correlation.
|
||||
func NewTraceHandler(h slog.Handler) *TraceHandler {
|
||||
return &TraceHandler{next: h}
|
||||
}
|
||||
|
||||
// Enabled implements slog.Handler.
|
||||
func (h *TraceHandler) Enabled(ctx context.Context, level slog.Level) bool {
|
||||
return h.next.Enabled(ctx, level)
|
||||
}
|
||||
|
||||
// Handle implements slog.Handler.
|
||||
func (h *TraceHandler) Handle(ctx context.Context, r slog.Record) error {
|
||||
if sc := trace.SpanContextFromContext(ctx); sc.IsValid() {
|
||||
r = r.Clone()
|
||||
r.AddAttrs(
|
||||
slog.String("trace_id", sc.TraceID().String()),
|
||||
slog.String("span_id", sc.SpanID().String()),
|
||||
)
|
||||
}
|
||||
return h.next.Handle(ctx, r)
|
||||
}
|
||||
|
||||
// WithAttrs implements slog.Handler.
|
||||
func (h *TraceHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
|
||||
return &TraceHandler{next: h.next.WithAttrs(attrs)}
|
||||
}
|
||||
|
||||
// WithGroup implements slog.Handler.
|
||||
func (h *TraceHandler) WithGroup(name string) slog.Handler {
|
||||
return &TraceHandler{next: h.next.WithGroup(name)}
|
||||
}
|
||||
|
||||
// durationAttr renders a duration as fractional milliseconds, which log
|
||||
// backends can aggregate directly (slog.Duration emits integer nanoseconds
|
||||
// in JSON).
|
||||
func durationAttr(d time.Duration) slog.Attr {
|
||||
return slog.Float64("duration_ms", float64(d.Microseconds())/1000)
|
||||
}
|
||||
Reference in new issue
Block a user