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

前言

uber开源的高性能日志库zap, 除了性能远超logrus之外,还有很多诱人的功能,比如支持日志采样、支持通过HTTP服务动态调整日志级别。不过他原生不支持文件归档,如果要支持文件按大小或者时间归档,必须要使用第三方库, 根据官方资料参考资料1,官方推荐的是 natefinch/lumberjack

示例

package main

import (
    "go.uber.org/zap"
    "go.uber.org/zap/zapcore"
    "gopkg.in/natefinch/lumberjack.v2"
)
// logpath 日志文件路径
// loglevel 日志级别
func initLogger(logpath string, loglevel string) *zap.Logger {

    hook := lumberjack.Logger{
        Filename:   logpath, // 日志文件路径
        MaxSize:    1024, // megabytes
        MaxBackups: 3,    // 最多保留3个备份
        MaxAge:     7,    //days
        Compress:   true, // 是否压缩 disabled by default
    }
    w := zapcore.AddSync(&hook)

    var level zapcore.Level
    switch loglevel {
    case "debug":
        level = zap.DebugLevel
    case "info":
        level = zap.InfoLevel
    case "error":
        level = zap.ErrorLevel
    default:
        level = zap.InfoLevel
    }
    encoderConfig := zap.NewProductionEncoderConfig()
    encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
    core := zapcore.NewCore(
        zapcore.NewConsoleEncoder(encoderConfig),
        w,
        level,
    )

    logger := zap.New(core)
    logger.Info("DefaultLogger init success")

    return logger
}

func main() {
    logger := initLogger("/tmp/all.log", "info")
    logger.Info("test log", zap.Int("line", 47))

}

文件的清理策略如下

Cleaning Up Old Log Files
Whenever a new logfile gets created, old log files may be deleted. The most recent files according to the encoded timestamp will be retained, up to a number equal to MaxBackups (or all of them if MaxBackups is 0). Any files with an encoded timestamp older than MaxAge days are deleted, regardless of MaxBackups. Note that the time encoded in the timestamp is the rotation time, which may differ from the last time that file was written to.

If MaxBackups and MaxAge are both 0, no old log files will be deleted.

总得而言就是MaxBackups和MaxAge 任意达到限制,对应的文件就会被清理

后记

使用了这个库之后就无法设置日志采样等原生的高级功能了

推荐阅读

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

参考资料

  1. zap–Frequently Asked Questions

如果我的文章对你有帮助,你可以给我打赏以促使我拿出更多的时间和精力来分享我的经验和思考总结。

微信支付码

发表评论

电子邮件地址不会被公开。 必填项已用*标注

This site uses Akismet to reduce spam. Learn how your comment data is processed.