Documentation ¶
Overview ¶
Package slogotel provides a custom handler for `log/slog` to ensures strong correlation between log records and Open-Telemetry spans.
Usage ¶
import ( "context" "log/slog" "go.opentelemetry.io/otel/baggage" "go.opentelemetry.io/otel/trace" sdktrace "go.opentelemetry.io/otel/sdk/trace" slogotel "github.com/DmitryKolbin/slog-otel" ) // 1. Configure slog. slog.SetDefault(slog.New(slogotel.OtelHandler{ Next: slog.NewJSONHandler(os.Stdout, nil), })) // 2. Set up your logger. logger := slog.Default() logger = logger.With("component", "server") // 3. (Optional) Add baggage to your context. m1, _ := baggage.NewMember("key_1", "value_1") m2, _ := baggage.NewMember("key_2", "value_2") bag, _ := baggage.New(m1, m2) ctx := baggage.ContextWithBaggage(context.Background(), bag) // 4. Start your span. tracer := sdktrace.NewTracerProvider().Tracer("server") ctx, span := tracer.Start(ctx, "operation-name") defer span.End() // 5. Log. logger.InfoContext(ctx, "Hello world!", "locale", "en_US")
Index ¶
Constants ¶
const ( // TraceIDKey is the key used by the Otel handler // to inject the trace ID in the log record. TraceIDKey = "trace_id" // SpanIDKey is the key used by the Otel handler // to inject the span ID in the log record. SpanIDKey = "span_id" // SpanEventKey is the key used by the Otel handler // to inject the log record in the recording span, as a span event. SpanEventKey = "log_record" )
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type HandlerFn ¶
HandlerFn defines the handler used by slog.Handler as return value.
func NewOtelHandler ¶
func NewOtelHandler() HandlerFn
NewOtelHandler creates and returns a new OtelHandler to use with log/slog.
type OtelHandler ¶
type OtelHandler struct { // Next represents the next handler in the chain. Next slog.Handler // NoBaggage determines whether to add context baggage members to the log record. NoBaggage bool }
OtelHandler is an implementation of slog's Handler interface. Its role is to ensure correlation between logs and OTel spans by:
1. Adding otel span and trace IDs to the log record. 2. Adding otel context baggage members to the log record. 3. Setting slog record as otel span event. 4. Adding slog record attributes to the otel span event. 5. Setting span status based on slog record level (only if >= slog.LevelError).
func (OtelHandler) Enabled ¶
Enabled reports whether the logger emits log records at the given context and level. Note: We handover the decision down to the next handler.
func (OtelHandler) Handle ¶
Handle handles the provided log record and adds correlation between a slog record and an Open-Telemetry span.