亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

Go
慕桂英4014372 2022-10-24 08:59:34
我將我的應用程序用作 SystemD 服務,并且需要在每條消息之前添加<LEVEL>JournalD 的入門級別,例如:<6> this is info<7> this is debug<4> this is warning否則,JournalD 將所有條目視為同一級別,我想使用其高級功能僅顯示特定級別的日志。如何<6>使用 uber-zap 庫在每個日志條目之前添加正確的級別標簽(例如 Info it would be )?編輯:這是我的記錄器配置的相關部分:    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"}
查看完整描述

1 回答

?
素胚勾勒不出你

TA貢獻1827條經驗 獲得超9個贊

您可以使用嵌入zapcore.Encoder.

嵌入編碼器使您可以“免費”使用您現在擁有的相同配置實現所有方法。然后,您只能EncodeEntry使用您需要的附加邏輯來實現。

注意:Clone()如果您計劃使用結構化日志記錄,您仍然必須實施,例如logger.With(). 更多信息:為什么在 Uber Zap 中調用 logger.With 后自定義編碼會丟失?

回到您的主要問題,這是一個工作示例;請參閱代碼中的注釋以獲取更多說明:

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")

}

測試運行輸出(INFO 打印為藍色,DEBUG 打印為粉紅色,WARN 打印為黃色,根據您的zapcore.CapitalColorLevelEncoder):


<6> INFO        this is info

<7> DEBUG       this is debug

<4> WARN        this is warn


查看完整回答
反對 回復 2022-10-24
  • 1 回答
  • 0 關注
  • 254 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號