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 关注
- 131 浏览
添加回答
举报