How to Log to STDOUT and STDERR Based on Log Level using Uber-Go/Zap?
Zap, a popular Go logging library, allows you to control where log messages are written based on their level. Here's how to configure Zap to write:
Using ZapCore.NewTee with Separate Cores:
To achieve this separation, create a tee core that combines two cores:
Here's an example program demonstrating this technique:
<code class="go">package main import ( "go.uber.org/zap" "go.uber.org/zap/zapcore" "os" ) func main() { // Level enablers 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 }) // Write syncers stdoutSyncer := zapcore.Lock(os.Stdout) stderrSyncer := zapcore.Lock(os.Stderr) // Tee core for InfoLevel and ErrorLevel/FatalLevel separation core := zapcore.NewTee( zapcore.NewCore( zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()), stdoutSyncer, infoLevel, ), zapcore.NewCore( zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()), stderrSyncer, errorFatalLevel, ), ) // Create logger with tee core logger := zap.New(core) logger.Info("Info log") logger.Error("Error log") }</code>
In this example, the program logs both an Info message to STDOUT and an Error message to STDERR. You can verify this by redirecting the respective outputs to /dev/null:
<code class="bash"># stdout only $ go build main.go && ./main 2>/dev/null { "level": "info", "ts": <timestamp>, "msg": "Info log" } # stderr only $ go build main.go && ./main 1>/dev/null { "level": "error", "ts": <timestamp>, "msg": "Error log" }</code>
The above is the detailed content of How to Separate Info Logs to STDOUT and Error/Fatal Logs to STDERR Using Uber-Go/Zap?. For more information, please follow other related articles on the PHP Chinese website!