From 0c557c5d725e170575ead7a315387f3a7f823ef6 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 --- act/common/testflag.go | 20 ++++++++++++++++++++ act/runner/logger.go | 6 ++++++ 2 files changed, 26 insertions(+) create mode 100644 act/common/testflag.go diff --git a/act/common/testflag.go b/act/common/testflag.go new file mode 100644 index 00000000..4988563d --- /dev/null +++ b/act/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/act/runner/logger.go b/act/runner/logger.go index 84648015..8da4bf1b 100644 --- a/act/runner/logger.go +++ b/act/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())