Documentation
¶
Overview ¶
Package slogotel provides an slog.Handler wrapper that bridges Go's log/slog with OpenTelemetry.
Unlike other slog-OpenTelemetry integrations, slogotel always injects trace_id and span_id as log attributes whenever a valid trace.SpanContext exists in the context, regardless of the Span's Recording state. When the Span is Recording, it additionally records log messages as Span events, injects Baggage members as log attributes, and sets the Span status to Error for error-level logs.
Usage ¶
h := slogotel.New(slog.NewJSONHandler(os.Stdout, nil)) logger := slog.New(h) logger.InfoContext(ctx, "request received", "path", "/api/users")
Options ¶
Use functional options to customize behavior:
h := slogotel.New(
slog.NewJSONHandler(os.Stdout, nil),
slogotel.WithSpanEvent(false), // disable Span event recording
slogotel.WithBaggage(false), // disable Baggage injection
slogotel.WithTraceIDKey("traceId"), // customize key names
slogotel.WithSpanIDKey("spanId"),
)
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
Handler is a slog.Handler that integrates with OpenTelemetry. It adds trace_id/span_id to log records regardless of Span recording state, and optionally records Span events, Baggage attributes, and error status only when the Span is recording.
func New ¶
New creates a new Handler wrapping the given slog.Handler. It panics if next is nil.
Example ¶
package main
import (
"log/slog"
"os"
"github.com/mocoarow/slogotel"
)
func main() {
h := slogotel.New(slog.NewJSONHandler(os.Stdout, nil))
logger := slog.New(h)
logger.Info("hello", "key", "value")
}
Output:
Example (WithOptions) ¶
package main
import (
"log/slog"
"os"
"github.com/mocoarow/slogotel"
)
func main() {
h := slogotel.New(
slog.NewJSONHandler(os.Stdout, nil),
slogotel.WithSpanEvent(false),
slogotel.WithBaggage(false),
slogotel.WithTraceIDKey("traceId"),
slogotel.WithSpanIDKey("spanId"),
slogotel.WithTraceFlagsKey("traceFlags"),
)
logger := slog.New(h)
logger.Info("hello", "key", "value")
}
Output:
type Option ¶
type Option func(*Handler)
Option configures a Handler.
func WithBaggage ¶
WithBaggage enables or disables adding Baggage members as log attributes. Default: true.
func WithSpanEvent ¶
WithSpanEvent enables or disables recording log messages as Span events. Default: true.
func WithSpanIDKey ¶
WithSpanIDKey sets the key name for span_id in log attributes. It panics if key is empty. Default: "span_id".
func WithTraceFlagsKey ¶
WithTraceFlagsKey sets the key name for trace_flags in log attributes. If empty, trace_flags will not be added. Default: "" (disabled).
func WithTraceIDKey ¶
WithTraceIDKey sets the key name for trace_id in log attributes. It panics if key is empty. Default: "trace_id".