2 回答

TA貢獻1963條經驗 獲得超6個贊
更好的答案:正如@Oliver Dain 所建議的,使用zap.AtomicLevel
. 有關詳細信息,請參閱他們的答案。
另一種選擇是創建具有自定義LevelEnabler
功能的核心。您可以使用zap.LevelEnablerFunc
將閉包轉換為zapcore.LevelEnabler
.
相關文檔:
LevelEnabler 決定在記錄消息時是否啟用給定的記錄級別。
LevelEnablerFunc 是使用匿名函數實現 zapcore.LevelEnabler 的便捷方式。
然后該函數可能會返回true
或false
基于在運行時更改的其他一些變量:
// will be actually initialized and changed at run time
// based on your business logic
var infoEnabled bool
errorUnlessEnabled := zap.LevelEnablerFunc(func(level zapcore.Level) bool {
// true: log message at this level
// false: skip message at this level
return level >= zapcore.ErrorLevel || infoEnabled
})
core := zapcore.NewCore(
zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()),
os.Stdout,
errorUnlessEnabled,
)
logger := zap.New(core)
logger.Info("foo") // not logged
infoEnabled = true
logger.Info("foo again") // logged
PS:這段代碼是人為的。您的程序必須在運行時實現初始化、值更改以及對infoEnabled變量進行適當的同步(如果需要)。
您可以在操場上運行此示例:https: //play.golang.org/p/oT3nvnP1Bwc

TA貢獻1786條經驗 獲得超11個贊
是的,可以使用AtomicLevel
. 從文檔:
atom := zap.NewAtomicLevel()
// To keep the example deterministic, disable timestamps in the output.
encoderCfg := zap.NewProductionEncoderConfig()
encoderCfg.TimeKey = ""
logger := zap.New(zapcore.NewCore(
zapcore.NewJSONEncoder(encoderCfg),
zapcore.Lock(os.Stdout),
atom,
))
defer logger.Sync()
logger.Info("info logging enabled")
atom.SetLevel(zap.ErrorLevel)
logger.Info("info logging disabled")
- 2 回答
- 0 關注
- 188 瀏覽
添加回答
舉報