繁体   English   中英

Uber Zap Logger:如何在每个日志条目前面加上一个字符串

[英]Uber Zap Logger: how to prepend every log entry with a string

我将我的应用程序用作 SystemD 服务,并且需要在每条消息之前为 JournalD 添加一个入门级<LEVEL> ,例如:

<6> this is info
<7> this is debug
<4> this is warning

否则,JournalD 将所有条目视为同一级别,我想使用其高级功能仅显示特定级别的日志。

如何使用 uber-zap 库为每个日志条目添加正确的级别 label (例如 Info 它将是<6> )?

编辑:这是我的记录器配置的相关部分:

    var config zap.Config

    if production {
        config = zap.NewProductionConfig()
        config.Encoding = `console`
        config.EncoderConfig.TimeKey = "" // no time as SystemD adds timestamp
    } else {
        config = zap.NewDevelopmentConfig()
    }

    config.DisableStacktrace = true
    config.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder // colors
    config.OutputPaths = []string{"stdout"}

您可以使用嵌入zapcore.Encoder的自定义编码器。

嵌入编码器使您可以“免费”使用您现在拥有的相同配置实现所有方法。 然后,您可以仅使用您需要的附加逻辑实现EncodeEntry 有关其他说明,请参见代码中的注释:

type prependEncoder struct {
    // embed a zapcore encoder
    // this makes prependEncoder implement the interface without extra work
    zapcore.Encoder

    // zap buffer pool
    pool buffer.Pool
}

// implementing only EncodeEntry
func (e *prependEncoder) EncodeEntry(entry zapcore.Entry, fields []zapcore.Field) (*buffer.Buffer, error) {
    // new log buffer
    buf := e.pool.Get()

    // prepend the JournalD prefix based on the entry level
    buf.AppendString(e.toJournaldPrefix(entry.Level))
    buf.AppendString(" ")

    // calling the embedded encoder's EncodeEntry to keep the original encoding format 
    consolebuf, err := e.Encoder.EncodeEntry(entry, fields)
    if err != nil {
        return nil, err
    }

    // just write the output into your own buffer
    _, err = buf.Write(consolebuf.Bytes())
    if err != nil {
        return nil, err
    }
    return buf, nil
}

// some mapper function
func (e *prependEncoder) toJournaldPrefix(lvl zapcore.Level) string {
    switch lvl {
    case zapcore.DebugLevel:
        return "<7>"
    case zapcore.InfoLevel:
        return "<6>"
    case zapcore.WarnLevel:
        return "<4>"
    }
    return ""
}

稍后,您将构建一个带有自定义核心的记录器,该核心使用自定义编码器。 您使用您现在使用的相同编码器初始化嵌入字段。 您在下面看到的选项模仿了您当前拥有的选项。

package main

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

func getConfig() zap.Config {
    // your current config options
    return config
}

func main() {
    cfg := getConfig()

    // constructing our prependEncoder with a ConsoleEncoder using your original configs
    enc := &prependEncoder{
        Encoder: zapcore.NewConsoleEncoder(cfg.EncoderConfig),
        pool:    buffer.NewPool(),
    }

    logger := zap.New(
        zapcore.NewCore(
            enc,
            os.Stdout,
            zapcore.DebugLevel,
        ),
        // this mimics the behavior of NewProductionConfig.Build
        zap.ErrorOutput(os.Stderr), 
    )

    logger.Info("this is info")
    logger.Debug("this is debug")
    logger.Warn("this is warn")
}

测试运行 output(根据您的zapcore.CapitalColorLevelEncoder ,INFO 打印为蓝色,DEBUG 打印为粉红色,WARN 打印为黄色):

<6> INFO        this is info
<7> DEBUG       this is debug
<4> WARN        this is warn

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM