如何配置uber-go/zap日志记录器以进行滚动文件系统日志?

huangapple go评论114阅读模式
英文:

How to configure uber-go/zap logger for rolling filesystem log?

问题

如何配置uber-go/zap日志记录器API,以将日志追加到指定的文件路径中。是否可以使其像滚动文件附加器一样工作(基于文件大小或日期),而不影响性能?

英文:

How to configure uber-go/zap logger api to append logs to a specified file-path. Can it be made to work like rolling file-appender (based on file-size or date) without affecting performance?

答案1

得分: 8

可以将一个钩子添加到zap日志记录器中,将条目写入lumberjack,这是一个用于Go的滚动日志。

一个简单的用法如下:

滚动日志:

// 在应用程序(或范围)退出时记得调用此函数:
// logger.Close()
var lumlog = &lumberjack.Logger{
Filename: "/tmp/my-zap.log",
MaxSize: 10, // 兆字节
MaxBackups: 3, // 日志文件数量
MaxAge: 3, // 天数
}

zap兼容的钩子:

func lumberjackZapHook(e zapcore.Entry) error {
lumlog.Write([]byte(fmt.Sprintf("%+v", e)))
return nil
}

然后像这样使用它:

logger, _ := zap.NewProduction(zap.Hooks(lumberjackZapHook))

**编辑1:**我不确定这是否符合您在性能方面的要求。有许多因素需要考虑。例如,使用SSD硬盘会有很大的差异,甚至可以将日志记录到一些时间序列数据库中进行批量写入。

**编辑2:**在zap的文档中,也使用了lumberjack(但不是作为钩子)。

英文:

A hook can be added to the zap logger which writes the entries to lumberjack, a rolling log for Go.

A simple usage would look like this:

The rolling log:

// remember to call this at app (or scope) exit:
// logger.Close()
var lumlog = &lumberjack.Logger{
	Filename:   "/tmp/my-zap.log",
	MaxSize:    10, // megabytes
	MaxBackups: 3,  // number of log files
	MaxAge:     3,  // days
}

The zap compatible hook:

func lumberjackZapHook(e zapcore.Entry) error {
	lumlog.Write([]byte(fmt.Sprintf("%+v", e)))
	return nil
}

And use it like:

logger, _ := zap.NewProduction(zap.Hooks(lumberjackZapHook))

Edit 1: I'm not sure if this meets your requirement in terms of performance. There are many factors there. For example using SSD hards make a big difference, or even logging into some timeseries databases with batch writes.

Edit 2: In zap documentation too, it uses lumberjack (but not as a hook).

答案2

得分: 1

如果你想在不使用钩子的情况下同时使用控制台日志和滚动日志,可以按照以下步骤进行操作:

// NewProductionZapLogger将返回一个由zap支持的新的生产日志记录器
func NewProductionZaplogger() (Logger, error) {
    conf := zap.NewProductionConfig()
    conf.Level = zap.NewAtomicLevelAt(zap.DebugLevel)
    conf.DisableCaller = true
    conf.DisableStacktrace = true
    zapLogger, err := conf.Build(zap.WrapCore(zapCore))

    return zpLg{
        lg: zapLogger.Sugar(),
    }, err
}

func zapCore(c zapcore.Core) zapcore.Core {
    // lumberjack.Logger已经可以安全地并发使用,所以我们不需要对它进行加锁。
    w := zapcore.AddSync(&lumberjack.Logger{
        Filename:   "./chat.log",
        MaxSize:    50, // 兆字节
        MaxBackups: 30,
        MaxAge:     28, // 天数
    })

    core := zapcore.NewCore(
        zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()),
        w,
        zap.DebugLevel,
    )
    cores := zapcore.NewTee(c, core)

    return cores
}

这段代码展示了如何同时使用控制台日志和滚动日志,而无需使用钩子。NewProductionZapLogger函数返回一个新的基于zap的生产日志记录器,zapCore函数用于创建zap核心。在zapCore函数中,我们使用lumberjack.Logger来创建滚动日志记录器,并将其与控制台日志记录器一起传递给zapcore.NewTee函数,以实现同时输出到两个地方的日志。

英文:

If you want to use both console log and rolling log without hook then you can do the following:

// NewProductionZapLogger will return a new production logger backed by zap
func NewProductionZaplogger() (Logger, error) {
	conf := zap.NewProductionConfig()
	conf.Level = zap.NewAtomicLevelAt(zap.DebugLevel)
	conf.DisableCaller = true
	conf.DisableStacktrace = true
	zapLogger, err := conf.Build(zap.WrapCore(zapCore))

	return zpLg{
		lg: zapLogger.Sugar(),
	}, err
}

func zapCore(c zapcore.Core) zapcore.Core {
	// lumberjack.Logger is already safe for concurrent use, so we don't need to
	// lock it.
	w := zapcore.AddSync(&lumberjack.Logger{
		Filename:   "./chat.log",
		MaxSize:    50, // megabytes
		MaxBackups: 30,
		MaxAge:     28, // days
	})

	core := zapcore.NewCore(
		zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()),
		w,
		zap.DebugLevel,
	)
	cores := zapcore.NewTee(c, core)

	return cores
}

答案3

得分: 0

我为zap和lumberjack编写了一个更简单的库rzap

rzap.NewGlobalLogger([]zapcore.Core{
    rzap.NewCore(&lumberjack.Logger{
        Filename:   "/your/log/path/app.log",
        MaxSize:    10,   // 10兆字节,默认为100兆字节
        MaxAge:     10,   // 10天,默认不删除旧日志文件
        MaxBackups: 10,   // 10个文件,默认保留所有旧日志文件
        Compress:   true, // 压缩为gzio,默认不执行压缩
    }, zap.InfoLevel),
})

zap.L().Info("一些消息", zap.Int("状态", 0))
英文:

I wrote a simpler library rzap for zap and lumberjack.

rzap.NewGlobalLogger([]zapcore.Core{
    rzap.NewCore(&lumberjack.Logger{
        Filename:   "/your/log/path/app.log",
        MaxSize:    10,   // 10 megabytes, defaults to 100 megabytes
        MaxAge:     10,   // 10 days, default is not to remove old log files
        MaxBackups: 10,   // 10 files, default is to retain all old log files
        Compress:   true, // compress to gzio, default is not to perform compression
    }, zap.InfoLevel),
})

zap.L().Info("some message", zap.Int("status", 0))

huangapple
  • 本文由 发表于 2017年8月1日 22:23:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/45440491.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定