|
| 1 | +package telemetry |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "log/slog" |
| 7 | + "time" |
| 8 | + |
| 9 | + "go.opentelemetry.io/otel/attribute" |
| 10 | + "go.opentelemetry.io/otel/baggage" |
| 11 | + "go.opentelemetry.io/otel/codes" |
| 12 | + "go.opentelemetry.io/otel/trace" |
| 13 | +) |
| 14 | + |
| 15 | +const ( |
| 16 | + // TraceIDKey is the key used by the Otel handler |
| 17 | + // to inject the trace ID in the log record. |
| 18 | + TraceIDKey = "TraceId" |
| 19 | + // SpanIDKey is the key used by the Otel handler |
| 20 | + // to inject the span ID in the log record. |
| 21 | + SpanIDKey = "SpanId" |
| 22 | + // SpanEventKey is the key used by the Otel handler |
| 23 | + // to inject the log record in the recording span, as a span event. |
| 24 | + SpanEventKey = "LogRecord" |
| 25 | +) |
| 26 | + |
| 27 | +// OtelHandler is an implementation of slog's Handler interface. |
| 28 | +// Its role is to ensure correlation between logs and OTel spans |
| 29 | +// by: |
| 30 | +// |
| 31 | +// 1. Adding otel span and trace IDs to the log record. |
| 32 | +// 2. Adding otel context baggage members to the log record. |
| 33 | +// 3. Setting slog record as otel span event. |
| 34 | +// 4. Adding slog record attributes to the otel span event. |
| 35 | +// 5. Setting span status based on slog record level (only if >= slog.LevelError). |
| 36 | +type OtelHandler struct { |
| 37 | + // Next represents the next handler in the chain. |
| 38 | + Next slog.Handler |
| 39 | + // NoBaggage determines whether to add context baggage members to the log record. |
| 40 | + NoBaggage bool |
| 41 | + // NoTraceEvents determines whether to record an event for every log on the active trace. |
| 42 | + NoTraceEvents bool |
| 43 | +} |
| 44 | + |
| 45 | +type OtelHandlerOpt func(handler *OtelHandler) |
| 46 | + |
| 47 | +// HandlerFn defines the handler used by slog.Handler as return value. |
| 48 | +type HandlerFn func(slog.Handler) slog.Handler |
| 49 | + |
| 50 | +// WithNoBaggage returns an OtelHandlerOpt, which sets the NoBaggage flag |
| 51 | +func WithNoBaggage(noBaggage bool) OtelHandlerOpt { |
| 52 | + return func(handler *OtelHandler) { |
| 53 | + handler.NoBaggage = noBaggage |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +// WithNoTraceEvents returns an OtelHandlerOpt, which sets the NoTraceEvents flag |
| 58 | +func WithNoTraceEvents(noTraceEvents bool) OtelHandlerOpt { |
| 59 | + return func(handler *OtelHandler) { |
| 60 | + handler.NoTraceEvents = noTraceEvents |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +// New creates a new OtelHandler to use with log/slog |
| 65 | +func New(next slog.Handler, opts ...OtelHandlerOpt) *OtelHandler { |
| 66 | + ret := &OtelHandler{ |
| 67 | + Next: next, |
| 68 | + } |
| 69 | + for _, opt := range opts { |
| 70 | + opt(ret) |
| 71 | + } |
| 72 | + return ret |
| 73 | +} |
| 74 | + |
| 75 | +// NewOtelHandler creates and returns a new HandlerFn, which wraps a handler with OtelHandler to use with log/slog. |
| 76 | +func NewOtelHandler(opts ...OtelHandlerOpt) HandlerFn { |
| 77 | + return func(next slog.Handler) slog.Handler { |
| 78 | + return New(next, opts...) |
| 79 | + } |
| 80 | +} |
| 81 | + |
| 82 | +// Handle handles the provided log record and adds correlation between a slog record and an Open-Telemetry span. |
| 83 | +func (h OtelHandler) Handle(ctx context.Context, record slog.Record) error { |
| 84 | + if ctx == nil { |
| 85 | + return h.Next.Handle(ctx, record) |
| 86 | + } |
| 87 | + |
| 88 | + if !h.NoBaggage { |
| 89 | + // Adding context baggage members to log record. |
| 90 | + b := baggage.FromContext(ctx) |
| 91 | + for _, m := range b.Members() { |
| 92 | + record.AddAttrs(slog.String(m.Key(), m.Value())) |
| 93 | + } |
| 94 | + } |
| 95 | + |
| 96 | + span := trace.SpanFromContext(ctx) |
| 97 | + if span == nil || !span.IsRecording() { |
| 98 | + return h.Next.Handle(ctx, record) |
| 99 | + } |
| 100 | + |
| 101 | + if !h.NoTraceEvents { |
| 102 | + // Adding log info to span event. |
| 103 | + eventAttrs := make([]attribute.KeyValue, 0, record.NumAttrs()) |
| 104 | + eventAttrs = append(eventAttrs, attribute.String(slog.MessageKey, record.Message)) |
| 105 | + eventAttrs = append(eventAttrs, attribute.String(slog.LevelKey, record.Level.String())) |
| 106 | + eventAttrs = append(eventAttrs, attribute.String(slog.TimeKey, record.Time.Format(time.RFC3339Nano))) |
| 107 | + record.Attrs(func(attr slog.Attr) bool { |
| 108 | + otelAttr := h.slogAttrToOtelAttr(attr) |
| 109 | + if otelAttr.Valid() { |
| 110 | + eventAttrs = append(eventAttrs, otelAttr) |
| 111 | + } |
| 112 | + |
| 113 | + return true |
| 114 | + }) |
| 115 | + |
| 116 | + span.AddEvent(SpanEventKey, trace.WithAttributes(eventAttrs...)) |
| 117 | + } |
| 118 | + |
| 119 | + // Adding span info to log record. |
| 120 | + spanContext := span.SpanContext() |
| 121 | + if spanContext.HasTraceID() { |
| 122 | + traceID := spanContext.TraceID().String() |
| 123 | + record.AddAttrs(slog.String(TraceIDKey, traceID)) |
| 124 | + } |
| 125 | + |
| 126 | + if spanContext.HasSpanID() { |
| 127 | + spanID := spanContext.SpanID().String() |
| 128 | + record.AddAttrs(slog.String(SpanIDKey, spanID)) |
| 129 | + } |
| 130 | + |
| 131 | + // Setting span status if the log is an error. |
| 132 | + // Purposely leaving as codes.Unset (default) otherwise. |
| 133 | + if record.Level >= slog.LevelError { |
| 134 | + span.SetStatus(codes.Error, record.Message) |
| 135 | + } |
| 136 | + |
| 137 | + return h.Next.Handle(ctx, record) |
| 138 | +} |
| 139 | + |
| 140 | +// WithAttrs returns a new Otel whose attributes consists of handler's attributes followed by attrs. |
| 141 | +func (h OtelHandler) WithAttrs(attrs []slog.Attr) slog.Handler { |
| 142 | + return OtelHandler{ |
| 143 | + Next: h.Next.WithAttrs(attrs), |
| 144 | + NoBaggage: h.NoBaggage, |
| 145 | + NoTraceEvents: h.NoTraceEvents, |
| 146 | + } |
| 147 | +} |
| 148 | + |
| 149 | +// WithGroup returns a new Otel with a group, provided the group's name. |
| 150 | +func (h OtelHandler) WithGroup(name string) slog.Handler { |
| 151 | + return OtelHandler{ |
| 152 | + Next: h.Next.WithGroup(name), |
| 153 | + NoBaggage: h.NoBaggage, |
| 154 | + NoTraceEvents: h.NoTraceEvents, |
| 155 | + } |
| 156 | +} |
| 157 | + |
| 158 | +// Enabled reports whether the logger emits log records at the given context and level. |
| 159 | +// Note: We handover the decision down to the next handler. |
| 160 | +func (h OtelHandler) Enabled(ctx context.Context, level slog.Level) bool { |
| 161 | + return h.Next.Enabled(ctx, level) |
| 162 | +} |
| 163 | + |
| 164 | +// slogAttrToOtelAttr converts a slog attribute to an OTel one. |
| 165 | +// Note: returns an empty attribute if the provided slog attribute is empty. |
| 166 | +func (h OtelHandler) slogAttrToOtelAttr(attr slog.Attr, groupKeys ...string) attribute.KeyValue { |
| 167 | + attr.Value = attr.Value.Resolve() |
| 168 | + if attr.Equal(slog.Attr{}) { |
| 169 | + return attribute.KeyValue{} |
| 170 | + } |
| 171 | + |
| 172 | + key := func(k string, prefixes ...string) string { |
| 173 | + for _, prefix := range prefixes { |
| 174 | + k = fmt.Sprintf("%s.%s", prefix, k) |
| 175 | + } |
| 176 | + |
| 177 | + return k |
| 178 | + }(attr.Key, groupKeys...) |
| 179 | + |
| 180 | + value := attr.Value.Resolve() |
| 181 | + |
| 182 | + switch attr.Value.Kind() { |
| 183 | + case slog.KindBool: |
| 184 | + return attribute.Bool(key, value.Bool()) |
| 185 | + case slog.KindFloat64: |
| 186 | + return attribute.Float64(key, value.Float64()) |
| 187 | + case slog.KindInt64: |
| 188 | + return attribute.Int64(key, value.Int64()) |
| 189 | + case slog.KindString: |
| 190 | + return attribute.String(key, value.String()) |
| 191 | + case slog.KindTime: |
| 192 | + return attribute.String(key, value.Time().Format(time.RFC3339Nano)) |
| 193 | + case slog.KindGroup: |
| 194 | + groupAttrs := value.Group() |
| 195 | + if len(groupAttrs) == 0 { |
| 196 | + return attribute.KeyValue{} |
| 197 | + } |
| 198 | + |
| 199 | + for _, groupAttr := range groupAttrs { |
| 200 | + return h.slogAttrToOtelAttr(groupAttr, append(groupKeys, key)...) |
| 201 | + } |
| 202 | + case slog.KindAny: |
| 203 | + switch v := attr.Value.Any().(type) { |
| 204 | + case []string: |
| 205 | + return attribute.StringSlice(key, v) |
| 206 | + case []int: |
| 207 | + return attribute.IntSlice(key, v) |
| 208 | + case []int64: |
| 209 | + return attribute.Int64Slice(key, v) |
| 210 | + case []float64: |
| 211 | + return attribute.Float64Slice(key, v) |
| 212 | + case []bool: |
| 213 | + return attribute.BoolSlice(key, v) |
| 214 | + default: |
| 215 | + return attribute.KeyValue{} |
| 216 | + } |
| 217 | + default: |
| 218 | + return attribute.KeyValue{} |
| 219 | + } |
| 220 | + |
| 221 | + return attribute.KeyValue{} |
| 222 | +} |
0 commit comments