go之logrus自定义日志样式
日志功能配置:logrus.go
package core import ( "bytes" "fmt" "github.com/sirupsen/logrus" "io" "os" "path" ) const ( red = 31 yellow = 33 blue = 36 gray = 37 ) type LogFormatter struct { } func (t LogFormatter) Format(entry *logrus.Entry) ([]byte, error) { //根据不同的level展示颜色 var levelColor int switch entry.Level { case logrus.DebugLevel, logrus.TraceLevel: levelColor = gray case logrus.WarnLevel: levelColor = yellow case logrus.ErrorLevel, logrus.FatalLevel, logrus.PanicLevel: levelColor = red default: levelColor = blue } //字节缓冲区 var b *bytes.Buffer if entry.Buffer != nil { b = entry.Buffer } else { b = &bytes.Buffer{} } //自定义日期格式 timestamp := entry.Time.Format("2006-01-02 15:04:06") if entry.HasCaller() { //自定义文件路径 funcVal := entry.Caller.Function fileVal := fmt.Sprintf("%s:%d", path.Base(entry.Caller.File), entry.Caller.Line) //自定义输出格式 fmt.Fprintf(b,"[%s] \033[%dm[%s]\033[0m %s %s %s \n",timestamp,levelColor,entry.Level,fileVal,funcVal,entry.Message) }else { fmt.Fprintf(b,"[%s] \033[%dm[%s]\033[0m %s %s %s \n",timestamp,levelColor,entry.Level,entry.Message) } return b.Bytes(),nil } func InitLogger() *logrus.Logger { mLog := logrus.New()//新建一个实例 file, _ := os.OpenFile("gin.log", os.O_CREATE|os.O_RDWR|os.O_APPEND, 0755) mLog.SetOutput(io.MultiWriter(os.Stdout,file))//设置输出类型 mLog.SetReportCaller(true)//开启返回函数名和行号 //mLog.SetFormatter(&logrus.JSONFormatter{})//设置自定义的Formatter mLog.SetFormatter(&LogFormatter{})//设置自定义的Formatter mLog.SetLevel(logrus.DebugLevel)//设置最低等级 return mLog }
全局变量:global.go
package global import ( "github.com/sirupsen/logrus" "gorm.io/gorm" "server/config" ) var ( Config *config.Config DB *gorm.DB Log *logrus.Logger )
程序入口:main.go
package main import ( "server/core" "server/global" ) //入口 func main() { //读取配置文件 core.InitConf() //初始化日志 global.Log = core.InitLogger() global.Log.Infoln("测试日志输出!") //fmt.Println(global.Config) global.DB = core.InitGorm() //返回值是db ,所以global.DB=db }
日志最终输出结果: