How to Output Logs to stdout and stderr Based on Log Level Using uber-go/zap
To separate logs based on severity level in uber-go/zap, utilize the concept of "tee-ing" zapcore cores. The approach leverages a tee core that combines two independent cores, each with specific level enablers.
Implementation:
Define Level Enablers:
<code class="go">infoLevel := zap.LevelEnablerFunc(func(level zapcore.Level) bool { return level == zapcore.InfoLevel }) errorFatalLevel := zap.LevelEnablerFunc(func(level zapcore.Level) bool { return level == zapcore.ErrorLevel || level == zapcore.FatalLevel })</code>
Set up Write Syncers:
<code class="go">stdoutSyncer := zapcore.Lock(os.Stdout) stderrSyncer := zapcore.Lock(os.Stderr)</code>
Construct Tee Core:
<code class="go">core := zapcore.NewTee( zapcore.NewCore( zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()), stdoutSyncer, infoLevel, ), zapcore.NewCore( zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()), stderrSyncer, errorFatalLevel, ), )</code>
Create Logger:
<code class="go">logger := zap.New(core)</code>
Demonstration:
<code class="go">logger.Info("info log") logger.Error("error log")</code>
Testing:
Redirect stdout or stderr to /dev/null to verify that info logs are printed to stdout and error logs to stderr:
$ go build main.go $ ./main 2>/dev/null # displays only stdout logs {"level":"info","ts":1626900981.520349,"msg":"info log"} $ ./main 1>/dev/null # displays only stderr logs {"level":"error","ts":1626901025.056065,"msg":"error log"}
The above is the detailed content of How to Separate Logs by Severity Level Using uber-go/zap?. For more information, please follow other related articles on the PHP Chinese website!