Home >Backend Development >Golang >How to Send Info Logs to stdout and Error/Fatal Logs to stderr Using uber-go/zap?

How to Send Info Logs to stdout and Error/Fatal Logs to stderr Using uber-go/zap?

Barbara Streisand
Barbara StreisandOriginal
2024-10-26 11:45:291010browse

How to Send Info Logs to stdout and Error/Fatal Logs to stderr Using uber-go/zap?

How to Log to stdout or stderr Based on Log Level Using uber-go/zap?

Problem:

Configure uber-go/zap to write info logs to stdout and error and fatal logs to stderr.

Answer:

To achieve this, use zapcore.NewTee with two cores, each set to handle specific log levels:

<code class="go">import (
    "go.uber.org/zap"
    "go.uber.org/zap/zapcore"
    "os"
)

func main() {
    // Create a level enabler for info logs
    infoLevel := zap.LevelEnablerFunc(func(level zapcore.Level) bool {
        return level == zapcore.InfoLevel
    })

    // Create a level enabler for error and fatal logs
    errorFatalLevel := zap.LevelEnablerFunc(func(level zapcore.Level) bool {
        return level == zapcore.ErrorLevel || level == zapcore.FatalLevel
    })

    // Create stdout and stderr writers
    stdoutSyncer := zapcore.Lock(os.Stdout)
    stderrSyncer := zapcore.Lock(os.Stderr)

    // Create a tee core that writes to both stdout and stderr
    core := zapcore.NewTee(
        // Core for info logs
        zapcore.NewCore(
            zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()),
            stdoutSyncer,
            infoLevel,
        ),
        // Core for error and fatal logs
        zapcore.NewCore(
            zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()),
            stderrSyncer,
            errorFatalLevel,
        ),
    )

    // Create a logger with the tee core
    logger := zap.New(core)

    // Log info and error messages
    logger.Info("info log")
    logger.Error("error log")
}</code>

This configuration allows you to control where different log levels are written to, providing greater flexibility in your logging strategy.

The above is the detailed content of How to Send 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