42 lines
804 B
Go
42 lines
804 B
Go
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
|
|
}
|