| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
package otelslog |
| 9 |
|
| 10 |
import ( |
| 11 |
"context" |
| 12 |
"fmt" |
| 13 |
"log/slog" |
| 14 |
"reflect" |
| 15 |
"runtime" |
| 16 |
"testing" |
| 17 |
"testing/slogtest" |
| 18 |
"time" |
| 19 |
|
| 20 |
"github.com/stretchr/testify/assert" |
| 21 |
"github.com/stretchr/testify/require" |
| 22 |
"go.opentelemetry.io/otel/attribute" |
| 23 |
"go.opentelemetry.io/otel/log" |
| 24 |
"go.opentelemetry.io/otel/log/embedded" |
| 25 |
"go.opentelemetry.io/otel/log/global" |
| 26 |
semconv "go.opentelemetry.io/otel/semconv/v1.40.0" |
| 27 |
) |
| 28 |
|
| 29 |
var now = time.Now() |
| 30 |
|
| 31 |
func TestNewLogger(t *testing.T) { |
| 32 |
assert.IsType(t, &Handler{}, NewLogger("").Handler()) |
| 33 |
} |
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
type embeddedLogger = embedded.Logger |
| 38 |
|
| 39 |
type scope struct { |
| 40 |
Name, Version, SchemaURL string |
| 41 |
Attributes attribute.Set |
| 42 |
} |
| 43 |
|
| 44 |
|
| 45 |
type recorder struct { |
| 46 |
embedded.LoggerProvider |
| 47 |
embeddedLogger |
| 48 |
|
| 49 |
|
| 50 |
Records []log.Record |
| 51 |
|
| 52 |
|
| 53 |
Scope scope |
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
MinSeverity log.Severity |
| 58 |
} |
| 59 |
|
| 60 |
func (r *recorder) Logger(name string, opts ...log.LoggerOption) log.Logger { |
| 61 |
cfg := log.NewLoggerConfig(opts...) |
| 62 |
|
| 63 |
r.Scope = scope{ |
| 64 |
Name: name, |
| 65 |
Version: cfg.InstrumentationVersion(), |
| 66 |
SchemaURL: cfg.SchemaURL(), |
| 67 |
Attributes: cfg.InstrumentationAttributes(), |
| 68 |
} |
| 69 |
return r |
| 70 |
} |
| 71 |
|
| 72 |
type enablerKey uint |
| 73 |
|
| 74 |
var enableKey enablerKey |
| 75 |
|
| 76 |
func (r *recorder) Enabled(ctx context.Context, param log.EnabledParameters) bool { |
| 77 |
return ctx.Value(enableKey) != nil || param.Severity >= r.MinSeverity |
| 78 |
} |
| 79 |
|
| 80 |
func (r *recorder) Emit(_ context.Context, record log.Record) { |
| 81 |
r.Records = append(r.Records, record) |
| 82 |
} |
| 83 |
|
| 84 |
func (r *recorder) Results() []map[string]any { |
| 85 |
out := make([]map[string]any, len(r.Records)) |
| 86 |
for i := range out { |
| 87 |
r := r.Records[i] |
| 88 |
|
| 89 |
m := make(map[string]any) |
| 90 |
if tStamp := r.Timestamp(); !tStamp.IsZero() { |
| 91 |
m[slog.TimeKey] = tStamp |
| 92 |
} |
| 93 |
if lvl := r.Severity(); lvl != 0 { |
| 94 |
m[slog.LevelKey] = lvl - 9 |
| 95 |
} |
| 96 |
if st := r.SeverityText(); st != "" { |
| 97 |
m["severityText"] = st |
| 98 |
} |
| 99 |
if body := r.Body(); body.Kind() != log.KindEmpty { |
| 100 |
m[slog.MessageKey] = value2Result(body) |
| 101 |
} |
| 102 |
r.WalkAttributes(func(kv log.KeyValue) bool { |
| 103 |
m[kv.Key] = value2Result(kv.Value) |
| 104 |
return true |
| 105 |
}) |
| 106 |
|
| 107 |
out[i] = m |
| 108 |
} |
| 109 |
return out |
| 110 |
} |
| 111 |
|
| 112 |
func value2Result(v log.Value) any { |
| 113 |
switch v.Kind() { |
| 114 |
case log.KindBool: |
| 115 |
return v.AsBool() |
| 116 |
case log.KindFloat64: |
| 117 |
return v.AsFloat64() |
| 118 |
case log.KindInt64: |
| 119 |
return v.AsInt64() |
| 120 |
case log.KindString: |
| 121 |
return v.AsString() |
| 122 |
case log.KindBytes: |
| 123 |
return v.AsBytes() |
| 124 |
case log.KindSlice: |
| 125 |
return v |
| 126 |
case log.KindMap: |
| 127 |
m := make(map[string]any) |
| 128 |
for _, val := range v.AsMap() { |
| 129 |
m[val.Key] = value2Result(val.Value) |
| 130 |
} |
| 131 |
return m |
| 132 |
} |
| 133 |
return nil |
| 134 |
} |
| 135 |
|
| 136 |
|
| 137 |
|
| 138 |
type testCase struct { |
| 139 |
|
| 140 |
name string |
| 141 |
|
| 142 |
explanation string |
| 143 |
|
| 144 |
|
| 145 |
|
| 146 |
|
| 147 |
f func(*slog.Logger) |
| 148 |
|
| 149 |
|
| 150 |
mod func(*slog.Record) |
| 151 |
|
| 152 |
|
| 153 |
checks [][]check |
| 154 |
|
| 155 |
options []Option |
| 156 |
} |
| 157 |
|
| 158 |
|
| 159 |
type check func(map[string]any) string |
| 160 |
|
| 161 |
|
| 162 |
func hasKey(key string) check { |
| 163 |
return func(m map[string]any) string { |
| 164 |
if _, ok := m[key]; !ok { |
| 165 |
return fmt.Sprintf("missing key %q", key) |
| 166 |
} |
| 167 |
return "" |
| 168 |
} |
| 169 |
} |
| 170 |
|
| 171 |
|
| 172 |
func missingKey(key string) check { |
| 173 |
return func(m map[string]any) string { |
| 174 |
if _, ok := m[key]; ok { |
| 175 |
return fmt.Sprintf("unexpected key %q", key) |
| 176 |
} |
| 177 |
return "" |
| 178 |
} |
| 179 |
} |
| 180 |
|
| 181 |
|
| 182 |
func hasAttr(key string, wantVal any) check { |
| 183 |
return func(m map[string]any) string { |
| 184 |
if s := hasKey(key)(m); s != "" { |
| 185 |
return s |
| 186 |
} |
| 187 |
gotVal := m[key] |
| 188 |
if !reflect.DeepEqual(gotVal, wantVal) { |
| 189 |
return fmt.Sprintf("%q: got %#v, want %#v", key, gotVal, wantVal) |
| 190 |
} |
| 191 |
return "" |
| 192 |
} |
| 193 |
} |
| 194 |
|
| 195 |
|
| 196 |
func inGroup(name string, c check) check { |
| 197 |
return func(m map[string]any) string { |
| 198 |
v, ok := m[name] |
| 199 |
if !ok { |
| 200 |
return fmt.Sprintf("missing group %q", name) |
| 201 |
} |
| 202 |
g, ok := v.(map[string]any) |
| 203 |
if !ok { |
| 204 |
return fmt.Sprintf("value for group %q is not map[string]any", name) |
| 205 |
} |
| 206 |
return c(g) |
| 207 |
} |
| 208 |
} |
| 209 |
|
| 210 |
|
| 211 |
func withSource(s string) string { |
| 212 |
_, file, line, ok := runtime.Caller(1) |
| 213 |
if !ok { |
| 214 |
panic("runtime.Caller failed") |
| 215 |
} |
| 216 |
return fmt.Sprintf("%s (%s:%d)", s, file, line) |
| 217 |
} |
| 218 |
|
| 219 |
|
| 220 |
type wrapper struct { |
| 221 |
slog.Handler |
| 222 |
mod func(*slog.Record) |
| 223 |
} |
| 224 |
|
| 225 |
|
| 226 |
func (h *wrapper) Handle(ctx context.Context, r slog.Record) error { |
| 227 |
h.mod(&r) |
| 228 |
return h.Handler.Handle(ctx, r) |
| 229 |
} |
| 230 |
|
| 231 |
func TestSLogHandler(t *testing.T) { |
| 232 |
|
| 233 |
pc, file, line, _ := runtime.Caller(0) |
| 234 |
funcName := runtime.FuncForPC(pc).Name() |
| 235 |
|
| 236 |
cases := []testCase{ |
| 237 |
{ |
| 238 |
name: "Values", |
| 239 |
explanation: withSource("all slog Values need to be supported"), |
| 240 |
f: func(l *slog.Logger) { |
| 241 |
l.Info( |
| 242 |
"msg", |
| 243 |
"any", struct{ data int64 }{data: 1}, |
| 244 |
"bool", true, |
| 245 |
"duration", time.Minute, |
| 246 |
"float64", 3.14159, |
| 247 |
"int64", -2, |
| 248 |
"string", "str", |
| 249 |
"time", now, |
| 250 |
"uint64", uint64(3), |
| 251 |
"nil", nil, |
| 252 |
"slice", []string{"foo", "bar"}, |
| 253 |
|
| 254 |
) |
| 255 |
}, |
| 256 |
checks: [][]check{{ |
| 257 |
hasKey(slog.TimeKey), |
| 258 |
hasKey(slog.LevelKey), |
| 259 |
hasAttr("severityText", "INFO"), |
| 260 |
hasAttr("any", "{data:1}"), |
| 261 |
hasAttr("bool", true), |
| 262 |
hasAttr("duration", int64(time.Minute)), |
| 263 |
hasAttr("float64", 3.14159), |
| 264 |
hasAttr("int64", int64(-2)), |
| 265 |
hasAttr("string", "str"), |
| 266 |
hasAttr("time", now.UnixNano()), |
| 267 |
hasAttr("uint64", int64(3)), |
| 268 |
hasAttr("nil", nil), |
| 269 |
hasAttr("slice", log.SliceValue(log.StringValue("foo"), log.StringValue("bar"))), |
| 270 |
}}, |
| 271 |
}, |
| 272 |
{ |
| 273 |
name: "multi-messages", |
| 274 |
explanation: withSource("this test expects multiple independent messages"), |
| 275 |
f: func(l *slog.Logger) { |
| 276 |
l.Warn("one") |
| 277 |
l.Debug("two") |
| 278 |
}, |
| 279 |
checks: [][]check{{ |
| 280 |
hasKey(slog.TimeKey), |
| 281 |
hasKey(slog.LevelKey), |
| 282 |
hasAttr("severityText", "WARN"), |
| 283 |
hasAttr(slog.MessageKey, "one"), |
| 284 |
}, { |
| 285 |
hasKey(slog.TimeKey), |
| 286 |
hasKey(slog.LevelKey), |
| 287 |
hasAttr("severityText", "DEBUG"), |
| 288 |
hasAttr(slog.MessageKey, "two"), |
| 289 |
}}, |
| 290 |
}, |
| 291 |
{ |
| 292 |
name: "multi-attrs", |
| 293 |
explanation: withSource("attributes from one message do not affect another"), |
| 294 |
f: func(l *slog.Logger) { |
| 295 |
l.Info("one", "k", "v") |
| 296 |
l.Info("two") |
| 297 |
}, |
| 298 |
checks: [][]check{{ |
| 299 |
hasAttr("k", "v"), |
| 300 |
}, { |
| 301 |
missingKey("k"), |
| 302 |
}}, |
| 303 |
}, |
| 304 |
{ |
| 305 |
name: "independent-WithAttrs", |
| 306 |
explanation: withSource("a Handler should only include attributes from its own WithAttr origin"), |
| 307 |
f: func(l *slog.Logger) { |
| 308 |
l1 := l.With("a", "b") |
| 309 |
l2 := l1.With("c", "d") |
| 310 |
l3 := l1.With("e", "f") |
| 311 |
|
| 312 |
l3.Info("msg", "k", "v") |
| 313 |
l2.Info("msg", "k", "v") |
| 314 |
l1.Info("msg", "k", "v") |
| 315 |
l.Info("msg", "k", "v") |
| 316 |
}, |
| 317 |
checks: [][]check{{ |
| 318 |
hasAttr("a", "b"), |
| 319 |
hasAttr("e", "f"), |
| 320 |
hasAttr("k", "v"), |
| 321 |
}, { |
| 322 |
hasAttr("a", "b"), |
| 323 |
hasAttr("c", "d"), |
| 324 |
hasAttr("k", "v"), |
| 325 |
missingKey("e"), |
| 326 |
}, { |
| 327 |
hasAttr("a", "b"), |
| 328 |
hasAttr("k", "v"), |
| 329 |
missingKey("c"), |
| 330 |
missingKey("e"), |
| 331 |
}, { |
| 332 |
hasAttr("k", "v"), |
| 333 |
missingKey("a"), |
| 334 |
missingKey("c"), |
| 335 |
missingKey("e"), |
| 336 |
}}, |
| 337 |
}, |
| 338 |
{ |
| 339 |
name: "independent-WithGroup", |
| 340 |
explanation: withSource("a Handler should only include attributes from its own WithGroup origin"), |
| 341 |
f: func(l *slog.Logger) { |
| 342 |
l1 := l.WithGroup("G").With("a", "b") |
| 343 |
l2 := l1.WithGroup("H").With("c", "d") |
| 344 |
l3 := l1.WithGroup("I").With("e", "f") |
| 345 |
|
| 346 |
l3.Info("msg", "k", "v") |
| 347 |
l2.Info("msg", "k", "v") |
| 348 |
l1.Info("msg", "k", "v") |
| 349 |
l.Info("msg", "k", "v") |
| 350 |
}, |
| 351 |
checks: [][]check{{ |
| 352 |
hasKey(slog.TimeKey), |
| 353 |
hasKey(slog.LevelKey), |
| 354 |
hasAttr("severityText", "INFO"), |
| 355 |
hasAttr(slog.MessageKey, "msg"), |
| 356 |
missingKey("a"), |
| 357 |
missingKey("c"), |
| 358 |
missingKey("H"), |
| 359 |
inGroup("G", hasAttr("a", "b")), |
| 360 |
inGroup("G", inGroup("I", hasAttr("e", "f"))), |
| 361 |
inGroup("G", inGroup("I", hasAttr("k", "v"))), |
| 362 |
}, { |
| 363 |
hasKey(slog.TimeKey), |
| 364 |
hasKey(slog.LevelKey), |
| 365 |
hasAttr(slog.MessageKey, "msg"), |
| 366 |
missingKey("a"), |
| 367 |
missingKey("c"), |
| 368 |
inGroup("G", hasAttr("a", "b")), |
| 369 |
inGroup("G", inGroup("H", hasAttr("c", "d"))), |
| 370 |
inGroup("G", inGroup("H", hasAttr("k", "v"))), |
| 371 |
}, { |
| 372 |
hasKey(slog.TimeKey), |
| 373 |
hasKey(slog.LevelKey), |
| 374 |
hasAttr(slog.MessageKey, "msg"), |
| 375 |
missingKey("a"), |
| 376 |
missingKey("c"), |
| 377 |
missingKey("H"), |
| 378 |
inGroup("G", hasAttr("a", "b")), |
| 379 |
inGroup("G", hasAttr("k", "v")), |
| 380 |
}, { |
| 381 |
hasKey(slog.TimeKey), |
| 382 |
hasKey(slog.LevelKey), |
| 383 |
hasAttr("k", "v"), |
| 384 |
hasAttr(slog.MessageKey, "msg"), |
| 385 |
missingKey("a"), |
| 386 |
missingKey("c"), |
| 387 |
missingKey("G"), |
| 388 |
missingKey("H"), |
| 389 |
}}, |
| 390 |
}, |
| 391 |
{ |
| 392 |
name: "independent-WithGroup.WithAttrs", |
| 393 |
explanation: withSource("a Handler should only include group attributes from its own WithAttr origin"), |
| 394 |
f: func(l *slog.Logger) { |
| 395 |
l = l.WithGroup("G") |
| 396 |
l.With("a", "b").Info("msg", "k", "v") |
| 397 |
l.With("c", "d").Info("msg", "k", "v") |
| 398 |
}, |
| 399 |
checks: [][]check{{ |
| 400 |
inGroup("G", hasAttr("a", "b")), |
| 401 |
inGroup("G", hasAttr("k", "v")), |
| 402 |
inGroup("G", missingKey("c")), |
| 403 |
}, { |
| 404 |
inGroup("G", hasAttr("c", "d")), |
| 405 |
inGroup("G", hasAttr("k", "v")), |
| 406 |
inGroup("G", missingKey("a")), |
| 407 |
}}, |
| 408 |
}, |
| 409 |
{ |
| 410 |
name: "WithSource", |
| 411 |
explanation: withSource("a Handler using the WithSource Option should include file attributes from where the log was emitted"), |
| 412 |
f: func(l *slog.Logger) { |
| 413 |
l.Info("msg") |
| 414 |
}, |
| 415 |
mod: func(r *slog.Record) { |
| 416 |
|
| 417 |
r.PC = pc |
| 418 |
}, |
| 419 |
checks: [][]check{{ |
| 420 |
hasAttr(string(semconv.CodeFilePathKey), file), |
| 421 |
hasAttr(string(semconv.CodeFunctionNameKey), funcName), |
| 422 |
hasAttr(string(semconv.CodeLineNumberKey), int64(line)), |
| 423 |
}}, |
| 424 |
options: []Option{WithSource(true)}, |
| 425 |
}, |
| 426 |
} |
| 427 |
|
| 428 |
|
| 429 |
for _, c := range cases { |
| 430 |
t.Run(c.name, func(t *testing.T) { |
| 431 |
r := new(recorder) |
| 432 |
opts := append([]Option{WithLoggerProvider(r)}, c.options...) |
| 433 |
var h slog.Handler = NewHandler("", opts...) |
| 434 |
if c.mod != nil { |
| 435 |
h = &wrapper{h, c.mod} |
| 436 |
} |
| 437 |
l := slog.New(h) |
| 438 |
c.f(l) |
| 439 |
got := r.Results() |
| 440 |
if len(got) != len(c.checks) { |
| 441 |
t.Fatalf("missing record checks: %d records, %d checks", len(got), len(c.checks)) |
| 442 |
} |
| 443 |
for i, checks := range c.checks { |
| 444 |
for _, check := range checks { |
| 445 |
if p := check(got[i]); p != "" { |
| 446 |
t.Errorf("%s: %s", p, c.explanation) |
| 447 |
} |
| 448 |
} |
| 449 |
} |
| 450 |
}) |
| 451 |
} |
| 452 |
} |
| 453 |
|
| 454 |
func TestSlogtest(t *testing.T) { |
| 455 |
r := new(recorder) |
| 456 |
slogtest.Run(t, func(*testing.T) slog.Handler { |
| 457 |
r = new(recorder) |
| 458 |
return NewHandler("", WithLoggerProvider(r)) |
| 459 |
}, func(*testing.T) map[string]any { |
| 460 |
return r.Results()[0] |
| 461 |
}) |
| 462 |
} |
| 463 |
|
| 464 |
func TestNewHandlerConfiguration(t *testing.T) { |
| 465 |
name := "name" |
| 466 |
t.Run("Default", func(t *testing.T) { |
| 467 |
r := new(recorder) |
| 468 |
prev := global.GetLoggerProvider() |
| 469 |
defer global.SetLoggerProvider(prev) |
| 470 |
global.SetLoggerProvider(r) |
| 471 |
|
| 472 |
var h *Handler |
| 473 |
require.NotPanics(t, func() { h = NewHandler(name) }) |
| 474 |
require.NotNil(t, h.logger) |
| 475 |
require.IsType(t, &recorder{}, h.logger) |
| 476 |
|
| 477 |
l := h.logger.(*recorder) |
| 478 |
want := scope{Name: name} |
| 479 |
assert.Equal(t, want, l.Scope) |
| 480 |
}) |
| 481 |
|
| 482 |
t.Run("Options", func(t *testing.T) { |
| 483 |
r := new(recorder) |
| 484 |
var h *Handler |
| 485 |
require.NotPanics(t, func() { |
| 486 |
h = NewHandler( |
| 487 |
name, |
| 488 |
WithLoggerProvider(r), |
| 489 |
WithVersion("ver"), |
| 490 |
WithSchemaURL("url"), |
| 491 |
WithSource(true), |
| 492 |
WithAttributes(attribute.String("testattr", "testval")), |
| 493 |
) |
| 494 |
}) |
| 495 |
require.NotNil(t, h.logger) |
| 496 |
require.IsType(t, &recorder{}, h.logger) |
| 497 |
|
| 498 |
l := h.logger.(*recorder) |
| 499 |
scope := scope{ |
| 500 |
Name: "name", |
| 501 |
Version: "ver", |
| 502 |
SchemaURL: "url", |
| 503 |
Attributes: attribute.NewSet(attribute.String("testattr", "testval")), |
| 504 |
} |
| 505 |
assert.Equal(t, scope, l.Scope) |
| 506 |
}) |
| 507 |
} |
| 508 |
|
| 509 |
func TestHandlerEnabled(t *testing.T) { |
| 510 |
r := new(recorder) |
| 511 |
r.MinSeverity = log.SeverityInfo |
| 512 |
|
| 513 |
h := NewHandler("name", WithLoggerProvider(r)) |
| 514 |
|
| 515 |
ctx := t.Context() |
| 516 |
assert.False(t, h.Enabled(ctx, slog.LevelDebug), "level conversion: permissive") |
| 517 |
assert.True(t, h.Enabled(ctx, slog.LevelInfo), "level conversion: restrictive") |
| 518 |
|
| 519 |
ctx = context.WithValue(ctx, enableKey, true) |
| 520 |
assert.True(t, h.Enabled(ctx, slog.LevelDebug), "context not passed") |
| 521 |
} |