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 <markus.wolf@new-work.se> Co-authored-by: Markus Wolf <markus.wolf@new-work.se>
This commit is contained in:
parent
f7263399b9
commit
6517d04b9a
2 changed files with 26 additions and 0 deletions
20
pkg/common/testflag.go
Normal file
20
pkg/common/testflag.go
Normal file
|
@ -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)
|
||||||
|
}
|
|
@ -48,6 +48,12 @@ func WithJobLogger(ctx context.Context, jobName string, secrets map[string]strin
|
||||||
nextColor++
|
nextColor++
|
||||||
|
|
||||||
logger := logrus.New()
|
logger := logrus.New()
|
||||||
|
if common.TestContext(ctx) {
|
||||||
|
fieldLogger := common.Logger(ctx)
|
||||||
|
if fieldLogger != nil {
|
||||||
|
logger = fieldLogger.(*logrus.Logger)
|
||||||
|
}
|
||||||
|
}
|
||||||
logger.SetFormatter(formatter)
|
logger.SetFormatter(formatter)
|
||||||
logger.SetOutput(os.Stdout)
|
logger.SetOutput(os.Stdout)
|
||||||
logger.SetLevel(logrus.GetLevel())
|
logger.SetLevel(logrus.GetLevel())
|
||||||
|
|
Loading…
Add table
Reference in a new issue