一、安装方法:
go get github.com/sirupsen/logrus
二、遇到问题:
如果没有翻墙无法下载golang.org/x/sys/unix包,
请参考:https://blog.csdn.net/wsliangjian/article/details/97253595,其他无法下载的golang.org的包均可参照此方法尝试
三、将日志写入指定文件并切割日志示例:
package main
import (
log "github.com/sirupsen/logrus"
"github.com/lestrrat-go/file-rotatelogs"
"github.com/rifflock/lfshook"
"time"
"github.com/pkg/errors"
"path"
)
func main() {
// 24小时一个日志文件,最多存365天的日志文件。 再多了就删掉
ConfigLocalFileSystemLogger("log", "lg", time.Second*30, time.Second*10)
for {
time.Sleep(time.Second * 3)
log.Info("hello ")
}
}
func ConfigLocalFileSystemLogger(logPath string, logFileName string, maxAge time.Duration, rotationTime time.Duration) {
baseLogPaht := path.Join(logPath, logFileName)
writer, err := rotatelogs.New(
baseLogPaht+".%Y%m%d%H%M", // 分割后的文件名称
rotatelogs.WithLinkName(baseLogPaht), // 生成软链,指向最新日志文件
rotatelogs.WithMaxAge(maxAge), // 设置最大保存时间(7天)
rotatelogs.WithRotationCount(365), // 最多存365个文件
rotatelogs.WithRotationTime(rotationTime), // 设置日志切割时间间隔(1天)
)
if err != nil {
log.Errorf("config local file system logger error. %+v", errors.WithStack(err))
}
lfHook := lfshook.NewHook(lfshook.WriterMap{
log.DebugLevel: writer, // 为不同级别设置不同的输出目的
log.InfoLevel: writer,
log.WarnLevel: writer,
log.ErrorLevel: writer,
log.FatalLevel: writer,
log.PanicLevel: writer,
}, &log.TextFormatter{})
log.AddHook(lfHook)
}