Home >Backend Development >Golang >How to Separate Logs by Severity Level Using uber-go/zap?

How to Separate Logs by Severity Level Using uber-go/zap?

Susan Sarandon
Susan SarandonOriginal
2024-10-25 08:59:29663browse

How to Separate Logs by Severity Level Using uber-go/zap?

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:

  1. 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>
  2. Set up Write Syncers:

    <code class="go">stdoutSyncer := zapcore.Lock(os.Stdout)
    stderrSyncer := zapcore.Lock(os.Stderr)</code>
  3. 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>
  4. 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
{&quot;level&quot;:&quot;info&quot;,&quot;ts&quot;:1626900981.520349,&quot;msg&quot;:&quot;info log&quot;}

$ ./main 1>/dev/null # displays only stderr logs
{&quot;level&quot;:&quot;error&quot;,&quot;ts&quot;:1626901025.056065,&quot;msg&quot;:&quot;error log&quot;}

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn