From 6517d04b9a4a677fc03277b6cf32fcd56a4dcf36 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B6rn=20Brauer?= Date: Sat, 27 Nov 2021 18:45:56 +0100 Subject: [PATCH] feat: allow existing logger from context (#898) We should reuse an existing context logger if in test context. This will allow test to setup act with a null logger to assert log messages. Co-authored-by: Markus Wolf Co-authored-by: Markus Wolf --- pkg/common/testflag.go | 20 ++++++++++++++++++++ pkg/runner/logger.go | 6 ++++++ 2 files changed, 26 insertions(+) create mode 100644 pkg/common/testflag.go diff --git a/pkg/common/testflag.go b/pkg/common/testflag.go new file mode 100644 index 0000000..4988563 --- /dev/null +++ b/pkg/common/testflag.go @@ -0,0 +1,20 @@ +package common + +import ( + "context" +) + +type testFlagContextKey string + +const testFlagContextKeyVal = testFlagContextKey("test-context") + +// TestContext returns whether the context has the test flag set +func TestContext(ctx context.Context) bool { + val := ctx.Value(testFlagContextKeyVal) + return val != nil +} + +// WithTextContext sets the test flag in the context +func WithTestContext(ctx context.Context) context.Context { + return context.WithValue(ctx, testFlagContextKeyVal, true) +} diff --git a/pkg/runner/logger.go b/pkg/runner/logger.go index 8464801..8da4bf1 100644 --- a/pkg/runner/logger.go +++ b/pkg/runner/logger.go @@ -48,6 +48,12 @@ func WithJobLogger(ctx context.Context, jobName string, secrets map[string]strin nextColor++ logger := logrus.New() + if common.TestContext(ctx) { + fieldLogger := common.Logger(ctx) + if fieldLogger != nil { + logger = fieldLogger.(*logrus.Logger) + } + } logger.SetFormatter(formatter) logger.SetOutput(os.Stdout) logger.SetLevel(logrus.GetLevel())