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] 🐹 Trivial/Minor

## Issue(s)

* #1630
This commit is contained in:
Keepers 2022-11-29 13:15:08 -07:00 committed by GitHub
parent eb67db2fa5
commit ff9a174d52
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -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)