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
Release: 2024-10-25 08:59:29
Original
677 people have browsed it

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>
    Copy after login
  2. Set up Write Syncers:

    <code class="go">stdoutSyncer := zapcore.Lock(os.Stdout)
    stderrSyncer := zapcore.Lock(os.Stderr)</code>
    Copy after login
  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>
    Copy after login
  4. Create Logger:

    <code class="go">logger := zap.New(core)</code>
    Copy after login

Demonstration:

<code class="go">logger.Info("info log")
logger.Error("error log")</code>
Copy after login

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;}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template