Fork me on GitHub

版权声明 本站原创文章 由 萌叔 发表
转载请注明 萌叔 | https://vearne.cc

引言

前几天有朋友问我,zap库是否支持同时打印到多个目标地址,比如1份打印到文件,1份到控制台,1份打印到kafka中。这是所有日志库都会支持的功能,zap当然也不例外。

示例

package main

import (
    "io/ioutil"
    "go.uber.org/zap"
    "go.uber.org/zap/zapcore"
    "gopkg.in/natefinch/lumberjack"
    "os"
)

func main(){
    // First, define our level-handling logic.
    // 仅打印Error级别以上的日志
    highPriority := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
        return lvl >= zapcore.ErrorLevel
    })
    // 打印所有级别的日志
    lowPriority := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
        return lvl >= zapcore.DebugLevel
    })

    hook := lumberjack.Logger{
        Filename:   "/tmp/abc.log",
        MaxSize:    1024, // megabytes
        MaxBackups: 3,
        MaxAge:     7,    //days
        Compress:   true, // disabled by default
    }


    topicErrors := zapcore.AddSync(ioutil.Discard)
    fileWriter := zapcore.AddSync(&hook)

    // High-priority output should also go to standard error, and low-priority
    // output should also go to standard out.
    consoleDebugging := zapcore.Lock(os.Stdout)

    // Optimize the Kafka output for machine consumption and the console output
    // for human operators.
    kafkaEncoder := zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig())
    consoleEncoder := zapcore.NewConsoleEncoder(zap.NewDevelopmentEncoderConfig())

    // Join the outputs, encoders, and level-handling functions into
    // zapcore.Cores, then tee the four cores together.
    core := zapcore.NewTee(
        // 打印在kafka topic中(伪造的case)
        zapcore.NewCore(kafkaEncoder, topicErrors, highPriority),
        // 打印在控制台
        zapcore.NewCore(consoleEncoder, consoleDebugging, lowPriority),
        // 打印在文件中
        zapcore.NewCore(consoleEncoder, fileWriter, highPriority),
    )

    // From a zapcore.Core, it's easy to construct a Logger.
    logger := zap.New(core)
    defer logger.Sync()
    logger.Info("constructed a info logger", zap.Int("test", 1))
    logger.Error("constructed a error logger", zap.Int("test", 2))
}

输出结果

文件中

2018-09-17T10:16:52.366+0800    ERROR   constructed a error logger  {"test": 2}

控制台

2018-09-17T10:16:52.365+0800    INFO    constructed a info logger   {"test": 1}
2018-09-17T10:16:52.366+0800    ERROR   constructed a error logger  {"test": 2}

推荐阅读

玩转高性能日志库zap (1)
玩转高性能日志库zap (2)


微信公众号

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注