如何使用 uber-go/zap 根据日志级别记录到 stdout 或 stderr?

How to log to stdout or stderr based on log level using uber-go/zap?

我正在尝试使用此包 github.com/uber-go/zap 设置日志记录。 我需要写:

我尝试通过如下设置和构建 zap.Config 来做到这一点:

    cfg = &zap.Config{
        Encoding:         "json",
        Level:            zap.NewAtomicLevelAt(zapcore.DebugLevel),
        OutputPaths:      []string{"stdout"},
        ErrorOutputPaths: []string{"stderr"},
        EncoderConfig: zapcore.EncoderConfig{
            MessageKey: "message",

            LevelKey:    "level",
            EncodeLevel: zapcore.CapitalLevelEncoder,

            TimeKey:    "time",
            EncodeTime: zapcore.ISO8601TimeEncoder,

            CallerKey:    "caller",
            EncodeCaller: zapcore.ShortCallerEncoder,

            EncodeDuration: zapcore.MillisDurationEncoder,
        },
    }

我也这样试过:

cfg = zap.NewProductionConfig()
    cfg.OutputPaths = []string{"stdout"}
    logger, err = cfg.Build(zap.AddCaller(), zap.AddCallerSkip(1))

但所有日志都写入标准输出 标准错误。我怎样才能把它分开?

使用两个核心的zapcore.NewTee

  • zapcore.InfoLevel 锁定到 stdout
  • zapcore.ErrorLevelzapcore.FatalLevel 锁定到 stderr

这是演示用法的最小程序:

package main

import (
    "go.uber.org/zap"
    "go.uber.org/zap/zapcore"
    "os"
)

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

    // error and fatal level enabler
    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
    core := zapcore.NewTee(
        zapcore.NewCore(
            zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()),
            stdoutSyncer,
            infoLevel,
        ),
        zapcore.NewCore(
            zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()),
            stderrSyncer,
            errorFatalLevel,
        ),
    )

    // finally construct the logger with the tee core
    logger := zap.New(core)

    logger.Info("info log")
    logger.Error("error log")
}

请注意,上面的程序记录了两条消息,一条是信息级别,一条是错误级别。要查看它是否都打印到正确的设备,运行 它并将 stdout 或 stderr 重定向到 /dev/null — 因此仅将另一个打印到控制台:

$ go build main.go

$ ./main 2>/dev/null # shows only stdout
{"level":"info","ts":1626900981.520349,"msg":"info log"}

$ ./main 1>/dev/null # shows only stderr
{"level":"error","ts":1626901025.056065,"msg":"error log"}