基于 logrus 和 file-rotatelogs 包实现日志切割

很多时候应用会将日志输出到文件系统,对于访问量大的应用来说日志的自动轮转切割管理是个很重要的问题,如果应用不能妥善处理日志管理,那么会带来很多不必要的维护开销:外部工具切割日志、人工清理日志等手段确保不会将磁盘打满。

file-rotatelogs: When you integrate this to to you app, it automatically write to logs that are rotated from within the app: No more disk-full alerts because you forgot to setup logrotate!

logrus 本身不支持日志轮转切割功能,需要配合 file-rotatelogs 包来实现,防止日志打满磁盘。file-rotatelogs 实现了 io.Writer 接口,并且提供了文件的切割功能,其实例可以作为 logrus 的目标输出,两者能无缝集成,这也是 file-rotatelogs 的设计初衷:

It's normally expected that this library is used with some other logging service, such as the built-in log library, or loggers such as github.com/lestrrat-go/apache-logformat.

示例代码:

应用日志文件 /Users/opensource/test/go.log,每隔 1 分钟轮转一个新文件,保留最近 3 分钟的日志文件,多余的自动清理掉。

package main

import (
 "time"

 rotatelogs "github.com/lestrrat-go/file-rotatelogs"
 log "github.com/sirupsen/logrus"
)

func init() {
 path := "/Users/opensource/test/go.log"
 /* 日志轮转相关函数
 `WithLinkName` 为最新的日志建立软连接
 `WithRotationTime` 设置日志分割的时间,隔多久分割一次
 WithMaxAge 和 WithRotationCount二者只能设置一个
  `WithMaxAge` 设置文件清理前的最长保存时间
  `WithRotationCount` 设置文件清理前最多保存的个数
 */
 // 下面配置日志每隔 1 分钟轮转一个新文件,保留最近 3 分钟的日志文件,多余的自动清理掉。
 writer, _ := rotatelogs.New(
 path+".%Y%m%d%H%M",
 rotatelogs.WithLinkName(path),
 rotatelogs.WithMaxAge(time.Duration(180)*time.Second),
 rotatelogs.WithRotationTime(time.Duration(60)*time.Second),
 )
 log.SetOutput(writer)
 //log.SetFormatter(&log.JSONFormatter{})
}

func main() {
 for {
 log.Info("hello, world!")
 time.Sleep(time.Duration(2) * time.Second)
 }
}