Codevault initial commit
This commit is contained in:
41
internal/observability/logging/ctx.go
Normal file
41
internal/observability/logging/ctx.go
Normal file
@@ -0,0 +1,41 @@
|
||||
package logging
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
type loggerKeyType int
|
||||
|
||||
const (
|
||||
loggerKey loggerKeyType = iota
|
||||
)
|
||||
|
||||
var ErrNotInitialized = errors.New("logger has not been initialized in the given context")
|
||||
|
||||
func CtxWithLogger(ctx context.Context, logger *zap.Logger) context.Context {
|
||||
if loggerCtx, ok := ctx.Value(loggerKey).(*zap.Logger); ok {
|
||||
if loggerCtx == logger {
|
||||
return ctx
|
||||
}
|
||||
}
|
||||
return context.WithValue(ctx, loggerKey, logger)
|
||||
}
|
||||
|
||||
func LoggerFromCtx(ctx context.Context) (*zap.Logger, error) {
|
||||
logger := ctx.Value(loggerKey)
|
||||
if logger == nil {
|
||||
return nil, ErrNotInitialized
|
||||
}
|
||||
return logger.(*zap.Logger), nil
|
||||
}
|
||||
|
||||
func LoggerMustFromContext(ctx context.Context) *zap.Logger {
|
||||
logger, err := LoggerFromCtx(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return logger
|
||||
}
|
||||
Reference in New Issue
Block a user