Skip to content

Commit

Permalink
otellogr: Fix nil context panic (#6527)
Browse files Browse the repository at this point in the history
  • Loading branch information
flc1125 authored Jan 20, 2025
1 parent 4e900d0 commit 45e0b8b
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 1 deletion.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm

## [Unreleased]

### Fixed

- Use `context.Background()` as default context instead of nil in `go.opentelemetry.io/contrib/bridges/otellogr`. (#6527)

<!-- Released section -->
<!-- Don't change this section unless doing release -->

Expand Down
3 changes: 2 additions & 1 deletion bridges/otellogr/logsink.go
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,7 @@ func NewLogSink(name string, options ...Option) *LogSink {
logger: c.provider.Logger(name, opts...),
levelSeverity: c.levelSeverity,
opts: opts,
ctx: context.Background(),
}
}

Expand Down Expand Up @@ -240,7 +241,7 @@ func (l *LogSink) Info(level int, msg string, keysAndValues ...any) {

// Init receives optional information about the logr library this
// implementation does not use it.
func (l *LogSink) Init(info logr.RuntimeInfo) {
func (l *LogSink) Init(logr.RuntimeInfo) {
// We don't need to do anything here.
// CallDepth is used to calculate the caller's PC.
// PC is dropped as part of the conversion to the OpenTelemetry log.Record.
Expand Down
34 changes: 34 additions & 0 deletions bridges/otellogr/logsink_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,40 @@ func TestLogSink(t *testing.T) {
}
}

// fix https://github.com/open-telemetry/opentelemetry-go-contrib/issues/6509
func TestLogSinkCtxInInfo(t *testing.T) {
rec := logtest.NewRecorder()
ls := NewLogSink("name", WithLoggerProvider(rec))
l := logr.New(ls)
ctx := context.WithValue(context.Background(), "key", "value") // nolint:revive,staticcheck

tests := []struct {
name string
keyValues []any
wantCtxFunc func(ctx context.Context)
}{
{"default", nil, func(ctx context.Context) {
assert.Equal(t, context.Background(), ctx)
}},
{"default with context", []any{"ctx", ctx}, func(ctx context.Context) {
assert.Equal(t, "value", ctx.Value("key"))
}},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
defer rec.Reset()

l.Info("msg", tt.keyValues...)
require.Len(t, rec.Result(), 1)

got := rec.Result()[0]
require.Len(t, got.Records, 1)
tt.wantCtxFunc(got.Records[0].Context())
})
}
}

func TestLogSinkEnabled(t *testing.T) {
enabledFunc := func(ctx context.Context, param log.EnabledParameters) bool {
return param.Severity == log.SeverityInfo
Expand Down

0 comments on commit 45e0b8b

Please sign in to comment.