簡體   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