diff --git a/go.mod b/go.mod index 8898fa9..062c611 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,3 @@ module github.com/chainguard-dev/clog -go 1.22.4 +go 1.24.4 diff --git a/slogtest/another_test.go b/slogtest/another_test.go new file mode 100644 index 0000000..1250d5c --- /dev/null +++ b/slogtest/another_test.go @@ -0,0 +1,9 @@ +package slogtest_test + +import ( + "context" + + "github.com/chainguard-dev/clog" +) + +func fn(ctx context.Context) { clog.FromContext(ctx).With("foo", "bar").Infof("hello from fn") } diff --git a/slogtest/slogtest.go b/slogtest/slogtest.go index 1fb98d8..9ab0db0 100644 --- a/slogtest/slogtest.go +++ b/slogtest/slogtest.go @@ -11,6 +11,11 @@ // slogtest.go:24: level=INFO source=/path/to/example_test.go:13 msg="hello world" foo=bar // // This package is intended to be used in tests only. +// +// In Go 1.24, *testing.T etc added `t.Context()` methods, which return a +// context.Context to be used in tests. You can use `clog.FromContext(t.Context())` +// to get a logger in tests instead, and configure the default logger to get the +// same logging behavior as `slogtest.Context(t)`. package slogtest import ( @@ -36,7 +41,10 @@ var _ Logger = (*testing.T)(nil) var _ Logger = (*testing.B)(nil) var _ Logger = (*testing.F)(nil) -type Logger interface{ Log(args ...any) } +type Logger interface { + Log(args ...any) + Context() context.Context +} // TestLogger gets a logger to use in unit and end to end tests. // This logger is configured to log at debug level. @@ -55,7 +63,7 @@ func TestLoggerWithOptions(t Logger, opts *slog.HandlerOptions) *clog.Logger { // Context returns a context with a logger to be used in tests. func Context(t Logger) context.Context { - return clog.WithLogger(context.Background(), TestLogger(t)) + return clog.WithLogger(t.Context(), TestLogger(t)) } // TestContextWithLogger returns a context with a logger to be used in tests diff --git a/slogtest/slogtest_test.go b/slogtest/slogtest_test.go index 62c03e5..f289c4f 100644 --- a/slogtest/slogtest_test.go +++ b/slogtest/slogtest_test.go @@ -1,6 +1,7 @@ package slogtest_test import ( + "log/slog" "testing" "github.com/chainguard-dev/clog" @@ -18,4 +19,23 @@ func TestSlogTest(t *testing.T) { clog.FromContext(ctx).Info("hello info") clog.FromContext(ctx).Warn("hello warn") clog.FromContext(ctx).Error("hello error") + + fn(ctx) +} + +// TestSlogTestTContext tests the use of t.Context() in Go 1.24+. +func TestSlogTestTContext(t *testing.T) { + ctx := t.Context() + slog.SetDefault(slog.New(slogtest.TestLogger(t).Handler())) + + clog.FromContext(ctx).With("foo", "bar").Infof("hello world") + clog.FromContext(ctx).With("bar", "baz").Infof("me again") + clog.FromContext(ctx).With("baz", true).Infof("okay last one") + + clog.FromContext(ctx).Debug("hello debug") + clog.FromContext(ctx).Info("hello info") + clog.FromContext(ctx).Warn("hello warn") + clog.FromContext(ctx).Error("hello error") + + fn(ctx) }