Home >Backend Development >Golang >How to Separate Info Logs to STDOUT and Error/Fatal Logs to STDERR Using Uber-Go/Zap?

How to Separate Info Logs to STDOUT and Error/Fatal Logs to STDERR Using Uber-Go/Zap?

DDD
DDDOriginal
2024-10-25 08:52:29330browse

How to Separate Info Logs to STDOUT and Error/Fatal Logs to STDERR Using Uber-Go/Zap?

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:

  • Info logs to STDOUT
  • Error and Fatal logs to STDERR

Using ZapCore.NewTee with Separate Cores:

To achieve this separation, create a tee core that combines two cores:

  • One core dedicated to the InfoLevel, writing to STDOUT.
  • Another core dedicated to ErrorLevel and FatalLevel, writing to STDERR.

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!

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