79

[uber-zap/part3]自定义记录器

 5 years ago
source link: https://studygolang.com/articles/19391?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

说明

  • 之前翻译的一个教程(没有备份原地址,梯子被封了)。原地址找到后补上

正文

zap 提供的字段编码器并一定完全合适自己的需求,比如:希望日志记录的输出和syslog或者其他常见的日志格式类似;可能希望日志中的时间戳忽略秒;将日志包含在方括号内等,这时候就需要自定义编码器了

性能因素

你可以自定义编码器 time , leve , caller 等。需要注意的是,编码器要尽可能高效,因为这是zap的内存、性能上的优势,毕竟每个日志行都要调用这些函数。所以要避免创建临时变量或者进行任何高强度的计算。

也就是说,下面的例子只是一个示范,不一定就是默认功能的最佳替代品。

自定义时间戳格式

这是一个常见的syslog格式的实现

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

func main() {
    cfg := zap.Config{
        Encoding:    "console",
        Level:       zap.NewAtomicLevelAt(zap.DebugLevel),
        OutputPaths: []string{"stderr"},

        EncoderConfig: zapcore.EncoderConfig{
            MessageKey: "message",

            TimeKey: "time",
        },
    }

    cfg.EncoderConfig.EncodeTime = SyslogTimeEncoder

    logger, _ := cfg.Build()
    logger.Info("This should have a syslog style timestamp")
}

输出

jan 1 09:22:59  This should have a syslog style timestamp

应该注意到,编码器应该将基元(primitives)附加到对象数组。zap使用此数组以最小的内存分配有效的编码输出

自定义级别格式

func CustomLevelEncoder(level zapcore.Level, enc zapcore.PrimitiveArrayEncoder) {
    enc.AppendString("[" + level.CapitalString() + "]")
}

func main() {
    cfg := zap.Config{
        Encoding:    "console",
        Level:       zap.NewAtomicLevelAt(zap.DebugLevel),
        OutputPaths: []string{"stderr"},

        EncoderConfig: zapcore.EncoderConfig{
            MessageKey: "message",

            LevelKey: "level",
        },
    }

    cfg.EncoderConfig.EncodeLevel = CustomLevelEncoder

    logger, _ := cfg.Build()
    logger.Info("This should have a bracketed level name")
}

输出

[INFO]  This should have a bracketed level name

注意:上面示例中,拼接多个子字符串形成一个字符串,并附加到数组中。这可能会导致临时内存分配。我不得不这样做,如果我单独附加子串,zap会将他们视为输出中的单独字段,并将它们用空格隔开


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK