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

我将我的应用程序用作 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"}


慕桂英4014372
浏览 246回答 1
1回答

素胚勾勒不出你

您可以使用嵌入zapcore.Encoder.嵌入编码器使您可以“免费”使用您现在拥有的相同配置实现所有方法。然后,您只能EncodeEntry使用您需要的附加逻辑来实现。注意:Clone()如果您计划使用结构化日志记录,您仍然必须实施,例如logger.With().&nbsp;更多信息:为什么在 Uber Zap 中调用 logger.With 后自定义编码会丢失?回到您的主要问题,这是一个工作示例;请参阅代码中的注释以获取更多说明:type prependEncoder struct {&nbsp; &nbsp; // embed a zapcore encoder&nbsp; &nbsp; // this makes prependEncoder implement the interface without extra work&nbsp; &nbsp; zapcore.Encoder&nbsp; &nbsp; // zap buffer pool&nbsp; &nbsp; pool buffer.Pool}// implementing only EncodeEntryfunc (e *prependEncoder) EncodeEntry(entry zapcore.Entry, fields []zapcore.Field) (*buffer.Buffer, error) {&nbsp; &nbsp; // new log buffer&nbsp; &nbsp; buf := e.pool.Get()&nbsp; &nbsp; // prepend the JournalD prefix based on the entry level&nbsp; &nbsp; buf.AppendString(e.toJournaldPrefix(entry.Level))&nbsp; &nbsp; buf.AppendString(" ")&nbsp; &nbsp; // calling the embedded encoder's EncodeEntry to keep the original encoding format&nbsp;&nbsp; &nbsp; consolebuf, err := e.Encoder.EncodeEntry(entry, fields)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return nil, err&nbsp; &nbsp; }&nbsp; &nbsp; // just write the output into your own buffer&nbsp; &nbsp; _, err = buf.Write(consolebuf.Bytes())&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return nil, err&nbsp; &nbsp; }&nbsp; &nbsp; return buf, nil}// some mapper functionfunc (e *prependEncoder) toJournaldPrefix(lvl zapcore.Level) string {&nbsp; &nbsp; switch lvl {&nbsp; &nbsp; case zapcore.DebugLevel:&nbsp; &nbsp; &nbsp; &nbsp; return "<7>"&nbsp; &nbsp; case zapcore.InfoLevel:&nbsp; &nbsp; &nbsp; &nbsp; return "<6>"&nbsp; &nbsp; case zapcore.WarnLevel:&nbsp; &nbsp; &nbsp; &nbsp; return "<4>"&nbsp; &nbsp; }&nbsp; &nbsp; return ""}稍后,您将构建一个带有自定义核心的记录器,该核心使用自定义编码器。您使用您现在使用的相同编码器初始化嵌入字段。您在下面看到的选项模仿了您当前拥有的选项。package mainimport (&nbsp; &nbsp; "go.uber.org/zap"&nbsp; &nbsp; "go.uber.org/zap/buffer"&nbsp; &nbsp; "go.uber.org/zap/zapcore"&nbsp; &nbsp; "os")func getConfig() zap.Config {&nbsp; &nbsp; // your current config options&nbsp; &nbsp; return config}func main() {&nbsp; &nbsp; cfg := getConfig()&nbsp; &nbsp; // constructing our prependEncoder with a ConsoleEncoder using your original configs&nbsp; &nbsp; enc := &prependEncoder{&nbsp; &nbsp; &nbsp; &nbsp; Encoder: zapcore.NewConsoleEncoder(cfg.EncoderConfig),&nbsp; &nbsp; &nbsp; &nbsp; pool:&nbsp; &nbsp; buffer.NewPool(),&nbsp; &nbsp; }&nbsp; &nbsp; logger := zap.New(&nbsp; &nbsp; &nbsp; &nbsp; zapcore.NewCore(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; enc,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; os.Stdout,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; zapcore.DebugLevel,&nbsp; &nbsp; &nbsp; &nbsp; ),&nbsp; &nbsp; &nbsp; &nbsp; // this mimics the behavior of NewProductionConfig.Build&nbsp; &nbsp; &nbsp; &nbsp; zap.ErrorOutput(os.Stderr),&nbsp;&nbsp; &nbsp; )&nbsp; &nbsp; logger.Info("this is info")&nbsp; &nbsp; logger.Debug("this is debug")&nbsp; &nbsp; logger.Warn("this is warn")}测试运行输出(INFO 打印为蓝色,DEBUG 打印为粉红色,WARN 打印为黄色,根据您的zapcore.CapitalColorLevelEncoder):<6> INFO&nbsp; &nbsp; &nbsp; &nbsp; this is info<7> DEBUG&nbsp; &nbsp; &nbsp; &nbsp;this is debug<4> WARN&nbsp; &nbsp; &nbsp; &nbsp; this is warn
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go