2 回答

TA貢獻1963條經(jīng)驗 獲得超6個贊
更好的答案:正如@Oliver Dain 所建議的,使用zap.AtomicLevel
. 有關(guān)詳細信息,請參閱他們的答案。
另一種選擇是創(chuàng)建具有自定義LevelEnabler
功能的核心。您可以使用zap.LevelEnablerFunc
將閉包轉(zhuǎn)換為zapcore.LevelEnabler
.
相關(guān)文檔:
LevelEnabler 決定在記錄消息時是否啟用給定的記錄級別。
LevelEnablerFunc 是使用匿名函數(shù)實現(xiàn) zapcore.LevelEnabler 的便捷方式。
然后該函數(shù)可能會返回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:這段代碼是人為的。您的程序必須在運行時實現(xiàn)初始化、值更改以及對infoEnabled變量進行適當?shù)耐剑ㄈ绻枰?/p>
您可以在操場上運行此示例:https: //play.golang.org/p/oT3nvnP1Bwc

TA貢獻1786條經(jīng)驗 獲得超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 關(guān)注
- 186 瀏覽
添加回答
舉報