Debian Codegraph @

bridges/otelslog/handler.go

raw symbols SCIP
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 // Package otelslog provides [Handler], an [slog.Handler] implementation, that
5 // can be used to bridge between the [log/slog] API and [OpenTelemetry].
6 //
7 // # Record Conversion
8 //
9 // The [slog.Record] are converted to OpenTelemetry [log.Record] in the following
10 // way:
11 //
12 // - Time is set as the Timestamp.
13 // - Message is set as the Body using a [log.StringValue].
14 // - Level is transformed and set as the Severity. The SeverityText is also
15 // set.
16 // - PC is dropped.
17 // - Attr are transformed and set as the Attributes.
18 //
19 // The Level is transformed by using the static offset to the OpenTelemetry
20 // Severity types. For example:
21 //
22 // - [slog.LevelDebug] is transformed to [log.SeverityDebug]
23 // - [slog.LevelInfo] is transformed to [log.SeverityInfo]
24 // - [slog.LevelWarn] is transformed to [log.SeverityWarn]
25 // - [slog.LevelError] is transformed to [log.SeverityError]
26 //
27 // Attribute values are transformed based on their [slog.Kind]:
28 //
29 // - [slog.KindAny] values are transformed based on their type or
30 // into a string value encoded using [fmt.Sprintf] if there is no matching type.
31 // - [slog.KindBool] are transformed to [log.BoolValue] directly.
32 // - [slog.KindDuration] are transformed to [log.Int64Value] as nanoseconds.
33 // - [slog.KindFloat64] are transformed to [log.Float64Value] directly.
34 // - [slog.KindInt64] are transformed to [log.Int64Value] directly.
35 // - [slog.KindString] are transformed to [log.StringValue] directly.
36 // - [slog.KindTime] are transformed to [log.Int64Value] as nanoseconds since
37 // the Unix epoch.
38 // - [slog.KindUint64] are transformed to [log.Int64Value] using int64
39 // conversion.
40 // - [slog.KindGroup] are transformed to [log.MapValue] using appropriate
41 // transforms for each group value.
42 // - [slog.KindLogValuer] the value is resolved and then transformed.
43 //
44 // [OpenTelemetry]: https://opentelemetry.io/docs/concepts/signals/logs/
45 package otelslog // import "go.opentelemetry.io/contrib/bridges/otelslog"
46
47 import (
48 "context"
49 "fmt"
50 "log/slog"
51 "runtime"
52 "slices"
53
54 "go.opentelemetry.io/otel/attribute"
55 "go.opentelemetry.io/otel/log"
56 "go.opentelemetry.io/otel/log/global"
57 semconv "go.opentelemetry.io/otel/semconv/v1.40.0"
58 )
59
60 // NewLogger returns a new [slog.Logger] backed by a new [Handler]. See
61 // [NewHandler] for details on how the backing Handler is created.
62 func NewLogger(name string, options ...Option) *slog.Logger {
63 return slog.New(NewHandler(name, options...))
64 }
65
66 type config struct {
67 provider log.LoggerProvider
68 version string
69 schemaURL string
70 attributes []attribute.KeyValue
71 source bool
72 }
73
74 func newConfig(options []Option) config {
75 var c config
76 for _, opt := range options {
77 c = opt.apply(c)
78 }
79
80 if c.provider == nil {
81 c.provider = global.GetLoggerProvider()
82 }
83
84 return c
85 }
86
87 func (c config) logger(name string) log.Logger {
88 var opts []log.LoggerOption
89 if c.version != "" {
90 opts = append(opts, log.WithInstrumentationVersion(c.version))
91 }
92 if c.schemaURL != "" {
93 opts = append(opts, log.WithSchemaURL(c.schemaURL))
94 }
95 if c.attributes != nil {
96 opts = append(opts, log.WithInstrumentationAttributes(c.attributes...))
97 }
98 return c.provider.Logger(name, opts...)
99 }
100
101 // Option configures a [Handler].
102 type Option interface {
103 apply(config) config
104 }
105
106 type optFunc func(config) config
107
108 func (f optFunc) apply(c config) config { return f(c) }
109
110 // WithVersion returns an [Option] that configures the version of the
111 // [log.Logger] used by a [Handler]. The version should be the version of the
112 // package that is being logged.
113 func WithVersion(version string) Option {
114 return optFunc(func(c config) config {
115 c.version = version
116 return c
117 })
118 }
119
120 // WithSchemaURL returns an [Option] that configures the semantic convention
121 // schema URL of the [log.Logger] used by a [Handler]. The schemaURL should be
122 // the schema URL for the semantic conventions used in log records.
123 func WithSchemaURL(schemaURL string) Option {
124 return optFunc(func(c config) config {
125 c.schemaURL = schemaURL
126 return c
127 })
128 }
129
130 // WithAttributes returns an [Option] that configures the instrumentation scope
131 // attributes of the [log.Logger] used by a [Handler].
132 func WithAttributes(attributes ...attribute.KeyValue) Option {
133 return optFunc(func(c config) config {
134 c.attributes = attributes
135 return c
136 })
137 }
138
139 // WithLoggerProvider returns an [Option] that configures [log.LoggerProvider]
140 // used by a [Handler] to create its [log.Logger].
141 //
142 // By default if this Option is not provided, the Handler will use the global
143 // LoggerProvider.
144 func WithLoggerProvider(provider log.LoggerProvider) Option {
145 return optFunc(func(c config) config {
146 c.provider = provider
147 return c
148 })
149 }
150
151 // WithSource returns an [Option] that configures the [Handler] to include
152 // the source location of the log record in log attributes.
153 func WithSource(source bool) Option {
154 return optFunc(func(c config) config {
155 c.source = source
156 return c
157 })
158 }
159
160 // Handler is an [slog.Handler] that sends all logging records it receives to
161 // OpenTelemetry. See package documentation for how conversions are made.
162 type Handler struct {
163 // Ensure forward compatibility by explicitly making this not comparable.
164 noCmp [0]func() //nolint:unused // This is indeed used.
165
166 attrs *kvBuffer
167 group *group
168 logger log.Logger
169
170 source bool
171 }
172
173 // Compile-time check *Handler implements slog.Handler.
174 var _ slog.Handler = (*Handler)(nil)
175
176 // NewHandler returns a new [Handler] to be used as an [slog.Handler].
177 //
178 // If [WithLoggerProvider] is not provided, the returned Handler will use the
179 // global LoggerProvider.
180 //
181 // The provided name needs to uniquely identify the code being logged. This is
182 // most commonly the package name of the code. If name is empty, the
183 // [log.Logger] implementation may override this value with a default.
184 func NewHandler(name string, options ...Option) *Handler {
185 cfg := newConfig(options)
186 return &Handler{
187 logger: cfg.logger(name),
188 source: cfg.source,
189 }
190 }
191
192 // Handle handles the passed record.
193 func (h *Handler) Handle(ctx context.Context, record slog.Record) error {
194 h.logger.Emit(ctx, h.convertRecord(record))
195 return nil
196 }
197
198 func (h *Handler) convertRecord(r slog.Record) log.Record {
199 var record log.Record
200 record.SetTimestamp(r.Time)
201 record.SetBody(log.StringValue(r.Message))
202
203 const sevOffset = slog.Level(log.SeverityDebug) - slog.LevelDebug
204 record.SetSeverity(log.Severity(r.Level + sevOffset))
205 record.SetSeverityText(r.Level.String())
206
207 if h.source {
208 fs := runtime.CallersFrames([]uintptr{r.PC})
209 f, _ := fs.Next()
210 record.AddAttributes(
211 log.String(string(semconv.CodeFilePathKey), f.File),
212 log.String(string(semconv.CodeFunctionNameKey), f.Function),
213 log.Int(string(semconv.CodeLineNumberKey), f.Line),
214 )
215 }
216
217 if h.attrs.Len() > 0 {
218 record.AddAttributes(h.attrs.KeyValues()...)
219 }
220
221 n := r.NumAttrs()
222 if h.group != nil {
223 if n > 0 {
224 buf := newKVBuffer(n)
225 r.Attrs(buf.AddAttr)
226 record.AddAttributes(h.group.KeyValue(buf.KeyValues()...))
227 } else {
228 // A Handler should not output groups if there are no attributes.
229 g := h.group.NextNonEmpty()
230 if g != nil {
231 record.AddAttributes(g.KeyValue())
232 }
233 }
234 } else if n > 0 {
235 buf := newKVBuffer(n)
236 r.Attrs(buf.AddAttr)
237 record.AddAttributes(buf.KeyValues()...)
238 }
239
240 return record
241 }
242
243 // Enabled returns true if the Handler is enabled to log for the provided
244 // context and Level. Otherwise, false is returned if it is not enabled.
245 func (h *Handler) Enabled(ctx context.Context, l slog.Level) bool {
246 const sevOffset = slog.Level(log.SeverityDebug) - slog.LevelDebug
247 param := log.EnabledParameters{Severity: log.Severity(l + sevOffset)}
248 return h.logger.Enabled(ctx, param)
249 }
250
251 // WithAttrs returns a new [slog.Handler] based on h that will log using the
252 // passed attrs.
253 func (h *Handler) WithAttrs(attrs []slog.Attr) slog.Handler {
254 h2 := *h
255 if h2.group != nil {
256 h2.group = h2.group.Clone()
257 h2.group.AddAttrs(attrs)
258 } else {
259 if h2.attrs == nil {
260 h2.attrs = newKVBuffer(len(attrs))
261 } else {
262 h2.attrs = h2.attrs.Clone()
263 }
264 h2.attrs.AddAttrs(attrs)
265 }
266 return &h2
267 }
268
269 // WithGroup returns a new [slog.Handler] based on h that will log all messages
270 // and attributes within a group of the provided name.
271 func (h *Handler) WithGroup(name string) slog.Handler {
272 h2 := *h
273 h2.group = &group{name: name, next: h2.group}
274 return &h2
275 }
276
277 // group represents a group received from slog.
278 type group struct {
279 // name is the name of the group.
280 name string
281 // attrs are the attributes associated with the group.
282 attrs *kvBuffer
283 // next points to the next group that holds this group.
284 //
285 // Groups are represented as map value types in OpenTelemetry. This means
286 // that for an slog group hierarchy like the following ...
287 //
288 // WithGroup("G").WithGroup("H").WithGroup("I")
289 //
290 // the corresponding OpenTelemetry log value types will have the following
291 // hierarchy ...
292 //
293 // KeyValue{
294 // Key: "G",
295 // Value: []KeyValue{{
296 // Key: "H",
297 // Value: []KeyValue{{
298 // Key: "I",
299 // Value: []KeyValue{},
300 // }},
301 // }},
302 // }
303 //
304 // When attributes are recorded (i.e. Info("msg", "key", "value") or
305 // WithAttrs("key", "value")) they need to be added to the "leaf" group. In
306 // the above example, that would be group "I":
307 //
308 // KeyValue{
309 // Key: "G",
310 // Value: []KeyValue{{
311 // Key: "H",
312 // Value: []KeyValue{{
313 // Key: "I",
314 // Value: []KeyValue{
315 // String("key", "value"),
316 // },
317 // }},
318 // }},
319 // }
320 //
321 // Therefore, groups are structured as a linked-list with the "leaf" node
322 // being the head of the list. Following the above example, the group data
323 // representation would be ...
324 //
325 // *group{"I", next: *group{"H", next: *group{"G"}}}
326 next *group
327 }
328
329 // NextNonEmpty returns the next group within g's linked-list that has
330 // attributes (including g itself). If no group is found, nil is returned.
331 func (g *group) NextNonEmpty() *group {
332 if g == nil || g.attrs.Len() > 0 {
333 return g
334 }
335 return g.next.NextNonEmpty()
336 }
337
338 // KeyValue returns group g containing kvs as a [log.KeyValue]. The value of
339 // the returned KeyValue will be of type [log.KindMap].
340 //
341 // The passed kvs are rendered in the returned value, but are not added to the
342 // group.
343 //
344 // This does not check g. It is the callers responsibility to ensure g is
345 // non-empty or kvs is non-empty so as to return a valid group representation
346 // (according to slog).
347 func (g *group) KeyValue(kvs ...log.KeyValue) log.KeyValue {
348 // Assumes checking of group g already performed (i.e. non-empty).
349 out := log.Map(g.name, g.attrs.KeyValues(kvs...)...)
350 g = g.next
351 for g != nil {
352 // A Handler should not output groups if there are no attributes.
353 if g.attrs.Len() > 0 {
354 out = log.Map(g.name, g.attrs.KeyValues(out)...)
355 }
356 g = g.next
357 }
358 return out
359 }
360
361 // Clone returns a copy of g.
362 func (g *group) Clone() *group {
363 if g == nil {
364 return nil
365 }
366 g2 := *g
367 g2.attrs = g2.attrs.Clone()
368 return &g2
369 }
370
371 // AddAttrs add attrs to g.
372 func (g *group) AddAttrs(attrs []slog.Attr) {
373 if g.attrs == nil {
374 g.attrs = newKVBuffer(len(attrs))
375 }
376 g.attrs.AddAttrs(attrs)
377 }
378
379 type kvBuffer struct {
380 data []log.KeyValue
381 }
382
383 func newKVBuffer(n int) *kvBuffer {
384 return &kvBuffer{data: make([]log.KeyValue, 0, n)}
385 }
386
387 // Len returns the number of [log.KeyValue] held by b.
388 func (b *kvBuffer) Len() int {
389 if b == nil {
390 return 0
391 }
392 return len(b.data)
393 }
394
395 // Clone returns a copy of b.
396 func (b *kvBuffer) Clone() *kvBuffer {
397 if b == nil {
398 return nil
399 }
400 return &kvBuffer{data: slices.Clone(b.data)}
401 }
402
403 // KeyValues returns kvs appended to the [log.KeyValue] held by b.
404 func (b *kvBuffer) KeyValues(kvs ...log.KeyValue) []log.KeyValue {
405 if b == nil {
406 return kvs
407 }
408 return append(b.data, kvs...)
409 }
410
411 // AddAttrs adds attrs to b.
412 func (b *kvBuffer) AddAttrs(attrs []slog.Attr) {
413 b.data = slices.Grow(b.data, len(attrs))
414 for _, a := range attrs {
415 _ = b.AddAttr(a)
416 }
417 }
418
419 // AddAttr adds attr to b and returns true.
420 //
421 // This is designed to be passed to the AddAttributes method of an
422 // [slog.Record].
423 //
424 // If attr is a group with an empty key, its values will be flattened.
425 //
426 // If attr is empty, it will be dropped.
427 func (b *kvBuffer) AddAttr(attr slog.Attr) bool {
428 if attr.Key == "" {
429 if attr.Value.Kind() == slog.KindGroup {
430 // A Handler should inline the Attrs of a group with an empty key.
431 for _, a := range attr.Value.Group() {
432 b.data = append(b.data, log.KeyValue{
433 Key: a.Key,
434 Value: convert(a.Value),
435 })
436 }
437 return true
438 }
439
440 if attr.Value.Any() == nil {
441 // A Handler should ignore an empty Attr.
442 return true
443 }
444 }
445 b.data = append(b.data, log.KeyValue{
446 Key: attr.Key,
447 Value: convert(attr.Value),
448 })
449 return true
450 }
451
452 func convert(v slog.Value) log.Value {
453 switch v.Kind() {
454 case slog.KindAny:
455 return convertValue(v.Any())
456 case slog.KindBool:
457 return log.BoolValue(v.Bool())
458 case slog.KindDuration:
459 return log.Int64Value(v.Duration().Nanoseconds())
460 case slog.KindFloat64:
461 return log.Float64Value(v.Float64())
462 case slog.KindInt64:
463 return log.Int64Value(v.Int64())
464 case slog.KindString:
465 return log.StringValue(v.String())
466 case slog.KindTime:
467 return log.Int64Value(v.Time().UnixNano())
468 case slog.KindUint64:
469 const maxInt64 = ^uint64(0) >> 1
470 u := v.Uint64()
471 if u > maxInt64 {
472 return log.Float64Value(float64(u))
473 }
474 return log.Int64Value(int64(u))
475 case slog.KindGroup:
476 g := v.Group()
477 buf := newKVBuffer(len(g))
478 buf.AddAttrs(g)
479 return log.MapValue(buf.data...)
480 case slog.KindLogValuer:
481 return convert(v.Resolve())
482 default:
483 // Try to handle this as gracefully as possible.
484 //
485 // Don't panic here. The goal here is to have developers find this
486 // first if a new slog.Kind is added. A test on the new kind will find
487 // this malformed attribute as well as a panic. However, it is
488 // preferable to have user's open issue asking why their attributes
489 // have a "unhandled: " prefix than say that their code is panicking.
490 return log.StringValue(fmt.Sprintf("unhandled: (%s) %+v", v.Kind(), v.Any()))
491 }
492 }