【Golang】自定义logrus日志保存为日志文件

背景

为了方便查看日志,项目中需要把日志保存到对应的日志文件中,所以需要当前的配置,以使得日志能够保存到对应的日志文件中。

代码


import (
	"github.com/orandin/lumberjackrus"
	"github.com/sirupsen/logrus"
)

func init() {
	logrus.AddHook(NewRotateHook())
}

func NewRotateHook() logrus.Hook {
	hook, _ := lumberjackrus.NewHook(
		&lumberjackrus.LogFile{
			// 通用日志配置
			Filename:   "output.log",
			MaxSize:    100,
			MaxBackups: 1,
			MaxAge:     1,
			Compress:   false,
			LocalTime:  false,
		},
		logrus.InfoLevel,
		&logrus.TextFormatter{DisableColors: true},
		&lumberjackrus.LogFileOpts{
			// 针对不同日志级别的配置
			logrus.TraceLevel: &lumberjackrus.LogFile{
				Filename: "trace.log",
				MaxSize:    100,
				MaxBackups: 1,
				MaxAge:     1,
				Compress:   false,
				LocalTime:  false,
			},
			logrus.DebugLevel: &lumberjackrus.LogFile{
				Filename: "debug.log",
				MaxSize:    100,
				MaxBackups: 1,
				MaxAge:     1,
				Compress:   false,
				LocalTime:  false,
			},
			logrus.InfoLevel: &lumberjackrus.LogFile{
				Filename: "info.log",
				MaxSize:    100,
				MaxBackups: 1,
				MaxAge:     1,
				Compress:   false,
				LocalTime:  false,
			},
			logrus.ErrorLevel: &lumberjackrus.LogFile{
				Filename:   "error.log",
				MaxSize:    10,   
				MaxBackups: 10,    
				MaxAge:     10,    
				Compress:   false,  
				LocalTime:  false, 
			},
			logrus.FatalLevel: &lumberjackrus.LogFile{
				Filename:   "fatal.log",
				MaxSize:    10,   
				MaxBackups: 10,    
				MaxAge:     10,    
				Compress:   false, 
				LocalTime:  false, 
			},
		},
	)
	return hook
}

你可能感兴趣的:(go,golang,数据库,开发语言)