dongpo9071 2018-12-03 14:31
浏览 74

具有自定义消息编码器的Uber Zap日志记录

I am using below code to dump logs on console and log file using Uber zap logger. I am looking how I can have a custom message encoder so that the output format for the message can be as below

{"severity":"DEBUG","message":"Dec 12, 2018  19:52:39 [log.go:77] Sample debug for log file and console"}

Below is the code which I am using to dump the logs on the console.

package main

import (
    "os"
    "time"

    "go.uber.org/zap"
    "go.uber.org/zap/zapcore"
    "gopkg.in/natefinch/lumberjack.v2"
    "path/filepath"
)

var logLevelSeverity = map[zapcore.Level]string{
    zapcore.DebugLevel:  "DEBUG",
    zapcore.InfoLevel:   "INFO",
    zapcore.WarnLevel:   "WARNING",
    zapcore.ErrorLevel:  "ERROR",
    zapcore.DPanicLevel: "CRITICAL",
    zapcore.PanicLevel:  "ALERT",
    zapcore.FatalLevel:  "EMERGENCY",
}

func SyslogTimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
    enc.AppendString(t.Format("Jan 01, 2006  15:04:05"))
}

func CustomEncodeLevel(level zapcore.Level, enc zapcore.PrimitiveArrayEncoder) {
    enc.AppendString(logLevelSeverity[level])
}

func CustomLevelFileEncoder(level zapcore.Level, enc zapcore.PrimitiveArrayEncoder) {
    enc.AppendString("[" + logLevelSeverity[level] + "]")
}
func funcCaller(caller zapcore.EntryCaller, enc zapcore.PrimitiveArrayEncoder) {
    enc.AppendString(filepath.Base(caller.FullPath()))
}

func main() {

    w := zapcore.AddSync(&lumberjack.Logger{
        Filename:   "temp1.log",
        MaxSize:    1024,
        MaxBackups: 20,
        MaxAge:     28,
        Compress:   true,
    })

    //Define config for the console output
    cfgConsole := zapcore.EncoderConfig{
        MessageKey:   "message",
        LevelKey:     "severity",
        EncodeLevel:  CustomEncodeLevel,
        TimeKey:      "time",
        EncodeTime:   SyslogTimeEncoder,
        CallerKey:    "caller",
        EncodeCaller: funcCaller,
    }
    cfgFile := zapcore.EncoderConfig{
        MessageKey:   "message",
        LevelKey:     "severity",
        EncodeLevel:  CustomLevelFileEncoder,
        TimeKey:      "time",
        EncodeTime:   SyslogTimeEncoder,
        CallerKey:    "caller",
        EncodeCaller: funcCaller,
    }

    consoleDebugging := zapcore.Lock(os.Stdout)
    //consoleError := zapcore.Lock(os.Stderr)
    core := zapcore.NewTee(
        zapcore.NewCore(zapcore.NewConsoleEncoder(cfgFile), w, zap.DebugLevel),
        zapcore.NewCore(zapcore.NewJSONEncoder(cfgConsole), consoleDebugging, zap.DebugLevel),
        //zapcore.NewCore(zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()), consoleError, zap.ErrorLevel),
    )
    //core := zapcore.NewCore(zapcore.NewConsoleEncoder(encConsole), w, zap.DebugLevel)
    wlogger := zap.New(core, zap.AddCaller())
    wlogger.Debug("Sample debug for log file and console")
    wlogger.Warn("An warning message example")
    wlogger.Info("An info level message")
    coreFile := zapcore.NewCore(zapcore.NewConsoleEncoder(cfgFile), w, zap.DebugLevel)
    flogger := zap.New(coreFile, zap.AddCaller())
    flogger.Debug("An exclusive message for file")
    //output
    //{"severity":"DEBUG","time":"Dec 12, 2018  19:52:39","caller":"log.go:77","message":"Sample debug for log file and console"}
}

Any thoughts how to achieve the expected output as we have an requirement for putting the message on the console in above format.

  • 写回答

1条回答 默认 最新

  • dongsou4301 2019-03-05 09:42
    关注

    Based on your code, the following configuration worked for me:

    func logInit(d bool, f *os.File) *zap.SugaredLogger {
    
        pe := zap.NewProductionEncoderConfig()
    
        fileEncoder := zapcore.NewJSONEncoder(pe)
    
        pe.EncodeTime = zapcore.ISO8601TimeEncoder
        consoleEncoder := zapcore.NewConsoleEncoder(pe)
    
        level := zap.InfoLevel
        if d {
            level = zap.DebugLevel
        }
    
        core := zapcore.NewTee(
            zapcore.NewCore(fileEncoder, zapcore.AddSync(f), level),
            zapcore.NewCore(consoleEncoder, zapcore.AddSync(os.Stdout), level),
        )
    
        l := zap.New(core)
    
        return l.Sugar()
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 MATLAB中streamslice问题
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序