logrus 日志管理
使用"github.com/sirupsen/logrus"、“github.com/rifflock/lfshook”、"github.com/lestrrat-go/file-rotatelogs"三个库进行项目的日志管理
"github.com/rifflock/lfshook"是一个用于将日志记录到本地文件系统的Golang库。 它提供了一个钩子(hook)来扩展Golang的标准日志库,使得在日志记录时可以将日志信息写入到本地文件系统中
"github.com/sirupsen/logrus"用来记录日志
"github.com/lestrrat-go/file-rotatelogs"它提供了一个钩子(hook)来扩展标准的日志库,实现日志文件的滚动记录
初始化日志
logger.InitLog(“log”, “log”, 10241024100, time.Hour247)
logPath:日志保存目录
logName:日志保存文件名
10241024100 : 日志保存滚动大小,这个100是100M
time.Hour247:最大日志保留日期,超过这个日期则进行清理
logger文件
package logger
import (
"fmt"
rotatelogs "github.com/lestrrat-go/file-rotatelogs"
"github.com/rifflock/lfshook"
log "github.com/sirupsen/logrus"
"os"
"path"
"path/filepath"
"strings"
"time"
)
type LogFileFormatter struct {
}
// 格式化处理
func (l LogFileFormatter) Format(entry *log.Entry) ([]byte, error) {
funcs := strings.SplitN(entry.Caller.Function, ".", 2)
msg := fmt.Sprintf("[%s] [%s] [%s:%d] %s\n",
entry.Time.Format("2006-01-02 15:04:05,000"),
strings.ToUpper(entry.Level.String()),
funcs[0]+"/"+filepath.Base(entry.Caller.File),
entry.Caller.Line,
entry.Message)
return []byte(msg), nil
}
func InitLog(logPath string, logName string, maxSize int64, maxAge time.Duration) {
filePaths := path.Join(logPath, logName)
writer, _ := rotatelogs.New(
filePaths+".%Y%m%d%H%M", //分割后文件名
rotatelogs.WithLinkName(filePaths), //软连接指向最新文件
rotatelogs.WithMaxAge(maxAge), // 最大保留时间(time.Hour*24*7) 一个星期
//rotatelogs.WithRotationTime(rotaTime), // 设置滚动时间
rotatelogs.WithRotationSize(maxSize), //设置日志文件最大存储大小为10MB (1024*1024*10)
)
writeMap := lfshook.WriterMap{
log.TraceLevel: writer,
log.DebugLevel: writer,
log.InfoLevel: writer,
log.WarnLevel: writer,
log.ErrorLevel: writer,
log.FatalLevel: writer,
log.PanicLevel: writer,
}
log.AddHook(lfshook.NewHook(writeMap, new(LogFileFormatter)))
log.SetOutput(os.Stdout)
log.SetReportCaller(true)
log.SetFormatter(&LogFileFormatter{})
}
初始化文件
package main
import (
"fmt"
log "github.com/sirupsen/logrus"
"test/core/logger"
"time"
)
// 在程序初始化的时候,进行初始化一下就可以了
func main() {
logger.InitLog("log", "log", 1024*1024*100, time.Hour*24*7)
for {
time.Sleep(time.Millisecond * 100)
log.Info(fmt.Sprintf("11111111111111111111111111111111111111111111111111"))
}
}