github.com/pingcap/br@v5.3.0-alpha.0.20220125034240-ec59c7b6ce30+incompatible/pkg/logutil/context.go (about)

     1  // Copyright 2020 PingCAP, Inc. Licensed under Apache-2.0.
     2  
     3  package logutil
     4  
     5  import (
     6  	"context"
     7  
     8  	"github.com/pingcap/log"
     9  	"go.uber.org/zap"
    10  )
    11  
    12  // We cannot directly set global logger as log.L(),
    13  // or when the global logger updated, we cannot get the latest logger.
    14  var globalLogger *zap.Logger = nil
    15  
    16  // ResetGlobalLogger resets the global logger.
    17  // Contexts have already made by `ContextWithField` would keep untouched,
    18  // subsequent wrapping over those contexts would keep using the old global logger,
    19  // only brand new contexts (i.e. context without logger) would be wrapped with the new global logger.
    20  // This method is mainly for testing.
    21  func ResetGlobalLogger(l *zap.Logger) {
    22  	globalLogger = l
    23  }
    24  
    25  type loggingContextKey struct{}
    26  
    27  var keyLogger loggingContextKey = loggingContextKey{}
    28  
    29  // ContextWithField wrap a context with a logger with some fields.
    30  func ContextWithField(c context.Context, fields ...zap.Field) context.Context {
    31  	logger := LoggerFromContext(c).With(fields...)
    32  	return context.WithValue(c, keyLogger, logger)
    33  }
    34  
    35  // LoggerFromContext returns the contextual logger via the context.
    36  // If there isn't a logger in the context, returns the global logger.
    37  func LoggerFromContext(c context.Context) *zap.Logger {
    38  	logger, ok := c.Value(keyLogger).(*zap.Logger)
    39  	if !ok {
    40  		if globalLogger != nil {
    41  			return globalLogger
    42  		}
    43  		return log.L()
    44  	}
    45  	return logger
    46  }
    47  
    48  // CL is the shorthand for LoggerFromContext.
    49  func CL(c context.Context) *zap.Logger {
    50  	return LoggerFromContext(c)
    51  }