1
0
mirror of https://github.com/open-telemetry/opentelemetry-go.git synced 2026-06-03 18:35:08 +02:00
Files
opentelemetry-go/log/logtest/example_test.go
T
Flc゛ 80cb909774 refactor: replace context.Background() with t.Context()/b.Context() in tests (#7352)
Based on the Go version we currently use, the dependency already
supports 1.24+, which allows using `t.Context()` and `b.Context()` in
unit tests and benchmarks respectively.

- Enable `context-background` and `context-todo` in
[`usetesting`](https://golangci-lint.run/docs/linters/configuration/#usetesting)
- Adjust the code to support linter detection

---------

Co-authored-by: Tyler Yahn <MrAlias@users.noreply.github.com>
Co-authored-by: Tyler Yahn <codingalias@gmail.com>
Co-authored-by: Damien Mathieu <42@dmathieu.com>
2025-09-23 09:52:45 +02:00

55 lines
1.2 KiB
Go

// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package logtest_test
import (
"testing"
"time"
"go.opentelemetry.io/otel/log"
"go.opentelemetry.io/otel/log/logtest"
)
func Example() {
t := &testing.T{} // Provided by testing framework.
// Create a recorder.
rec := logtest.NewRecorder()
// Emit a log record (code under test).
l := rec.Logger("Example")
r := log.Record{}
r.SetTimestamp(time.Now())
r.SetSeverity(log.SeverityInfo)
r.SetBody(log.StringValue("Hello there"))
r.AddAttributes(log.String("foo", "bar"))
r.AddAttributes(log.Int("n", 1))
l.Emit(t.Context(), r)
// Verify that the expected and actual log records match.
want := logtest.Recording{
logtest.Scope{Name: "Example"}: []logtest.Record{
{
Severity: log.SeverityInfo,
Body: log.StringValue("Hello there"),
Attributes: []log.KeyValue{
log.Int("n", 1),
log.String("foo", "bar"),
},
},
},
}
got := rec.Result()
logtest.AssertEqual(t, want, got,
logtest.Transform(func(r logtest.Record) logtest.Record {
r = r.Clone()
r.Context = nil // Ignore context.
r.Timestamp = time.Time{} // Ignore timestamp.
return r
}),
)
// Output:
//
}