From ff9a174d52671ce2306c1df8a30e7e0d329bf3a5 Mon Sep 17 00:00:00 2001 From: Keepers Date: Tue, 29 Nov 2022 13:15:08 -0700 Subject: [PATCH] add Set func to logger package (#1631) ## Description Add a Set(ctx, logger) func to the logger package to allow SDK users to provide their own zap logger instance to corso. ## Type of change - [x] :hamster: Trivial/Minor ## Issue(s) * #1630 --- src/pkg/logger/logger.go | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/src/pkg/logger/logger.go b/src/pkg/logger/logger.go index 6befdb85b..b9e413d18 100644 --- a/src/pkg/logger/logger.go +++ b/src/pkg/logger/logger.go @@ -149,7 +149,7 @@ type loggingKey string const ctxKey loggingKey = "corsoLogger" -// Seed embeds a logger into the context for later retrieval. +// Seed generates a logger within the context for later retrieval. // It also parses the command line for flag values prior to executing // cobra. This early parsing is necessary since logging depends on // a seeded context prior to cobra evaluating flags. @@ -159,24 +159,30 @@ func Seed(ctx context.Context, lvl string) (context.Context, *zap.SugaredLogger) } zsl := singleton(levelOf(lvl)) - ctxOut := context.WithValue(ctx, ctxKey, zsl) - return ctxOut, zsl + return Set(ctx, zsl), zsl } -// SeedLevel embeds a logger into the context with the given log-level. +// SeedLevel generates a logger within the context with the given log-level. func SeedLevel(ctx context.Context, level logLevel) (context.Context, *zap.SugaredLogger) { l := ctx.Value(ctxKey) if l == nil { zsl := singleton(level) - ctxWV := context.WithValue(ctx, ctxKey, zsl) - - return ctxWV, zsl + return Set(ctx, zsl), zsl } return ctx, l.(*zap.SugaredLogger) } +// Set allows users to embed their own zap.SugaredLogger within the context. +func Set(ctx context.Context, logger *zap.SugaredLogger) context.Context { + if logger == nil { + return ctx + } + + return context.WithValue(ctx, ctxKey, logger) +} + // Ctx retrieves the logger embedded in the context. func Ctx(ctx context.Context) *zap.SugaredLogger { l := ctx.Value(ctxKey)