hertz-contrib/logger

In multiple zapcore examples, how do I use the LevelEnablerFunc filter to make the debug file log only the Debug level and the Info file record only the INFO level log

Closed this issue · 5 comments

In multiple zapcore examples, how do I use the LevelEnablerFunc filter to make the Info file record only the INFO level log,and also, other files also correspond to the level

Just following the readme instructions.
It seems there is a missing line that needs to be added.
hlog.SetLogger(logger) after logger init.

Just following the readme instructions. It seems there is a missing line that needs to be added. hlog.SetLogger(logger) after logger init.

My code follows the demo completely and adds hlog.SetLogger, but the info.log file contains both info and error level logs. I hope info.log only contains logs of info level, and debug.log only contains logs of debug level.

Here we use AtomicLevel to implement the SetLevel method of hlog. If you don't need the SetLevel method, you can use logger like this.

logger := hertzzap.NewLogger(
	hertzzap.WithZapOptions(zap.WrapCore(func(core zapcore.Core) zapcore.Core {
		return zapcore.NewTee(
			zapcore.NewCore(
				zapcore.NewJSONEncoder(humanEncoderConfig()), getWriteSyncer("log/debug.log"), zap.LevelEnablerFunc(func(level zapcore.Level) bool {
					return level == zap.DebugLevel
				}),
			),
			zapcore.NewCore(
				zapcore.NewJSONEncoder(humanEncoderConfig()), getWriteSyncer("log/info.log"), zap.LevelEnablerFunc(func(level zapcore.Level) bool {
					return level == zap.InfoLevel
				}),
			),
			zapcore.NewCore(
				zapcore.NewJSONEncoder(humanEncoderConfig()), getWriteSyncer("log/warn.log"), zap.LevelEnablerFunc(func(level zapcore.Level) bool {
					return level == zap.WarnLevel
				}),
			),
		)
	}),
	),
)
defer logger.Sync()

hlog.SetLogger(logger)

这里我们使用AtomicLevel来实现hlog的SetLevel方法。如果不需要 SetLevel 方法,可以像这样使用 logger。

logger := hertzzap.NewLogger(
	hertzzap.WithZapOptions(zap.WrapCore(func(core zapcore.Core) zapcore.Core {
		return zapcore.NewTee(
			zapcore.NewCore(
				zapcore.NewJSONEncoder(humanEncoderConfig()), getWriteSyncer("log/debug.log"), zap.LevelEnablerFunc(func(level zapcore.Level) bool {
					return level == zap.DebugLevel
				}),
			),
			zapcore.NewCore(
				zapcore.NewJSONEncoder(humanEncoderConfig()), getWriteSyncer("log/info.log"), zap.LevelEnablerFunc(func(level zapcore.Level) bool {
					return level == zap.InfoLevel
				}),
			),
			zapcore.NewCore(
				zapcore.NewJSONEncoder(humanEncoderConfig()), getWriteSyncer("log/warn.log"), zap.LevelEnablerFunc(func(level zapcore.Level) bool {
					return level == zap.WarnLevel
				}),
			),
		)
	}),
	),
)
defer logger.Sync()

hlog.SetLogger(logger)

thanks, It works

#27

The new version fixed this issue, and you can also refer to the latest version readme for usage instructions.