簡單記錄一下logrus實戰應用,詳細瞭解可以移步官網,這是直接使用
上程式碼:
logrus整個專案應用封裝
package log
import (
"fmt"
"github.com/sirupsen/logrus"
"go_service/config"
"os"
"path"
"time"
)
var log = logrus.New()
func Debug(fileds logrus.Fields,args ...interface{}) {
setOutPutFile(logrus.DebugLevel,fileds ,args)
logrus.WithFields(fileds).Debug(args)
}
func Info(fileds logrus.Fields,args ...interface{}) {
setOutPutFile(logrus.InfoLevel,fileds ,args)
logrus.WithFields(fileds).Info(args)
}
func Warn(fileds logrus.Fields,args ...interface{}) {
setOutPutFile(logrus.WarnLevel,fileds ,args)
logrus.WithFields(fileds).Warn(args)
}
func Fatal(fileds logrus.Fields,args ...interface{}) {
setOutPutFile(logrus.FatalLevel,fileds ,args)
logrus.WithFields(fileds).Fatal(args)
}
func Error(fileds logrus.Fields,args ...interface{}) {
setOutPutFile(logrus.ErrorLevel,fileds ,args)
log.WithFields(fileds).Error(args)
}
func Panic(fileds logrus.Fields,args ...interface{}) {
setOutPutFile(logrus.PanicLevel,fileds ,args)
logrus.WithFields(fileds).Panic(args)
}
func Trace(fileds logrus.Fields,args ...interface{}) {
setOutPutFile(logrus.TraceLevel,fileds ,args)
logrus.WithFields(fileds).Trace(args)
}
//level logrus.Level
func setOutPutFile(level logrus.Level,fileds logrus.Fields,args ...interface{}) {
if _,err := os.Stat(config.BaseConf.Log.Dir);os.IsNotExist(err){
err = os.MkdirAll(config.BaseConf.Log.Dir,0777)
if err != nil {
panic(fmt.Errorf("create log dir '%s' error:%s",config.BaseConf.Log.Dir,err))
}
}
fileName := path.Join("./"+config.BaseConf.Log.Dir,time.Now().Format("2006-01-02") + ".log")
var err error
files,err := os.OpenFile(fileName,os.O_WRONLY|os.O_APPEND|os.O_SYNC|os.O_CREATE|os.O_RDWR,0766)
if err != nil{
fmt.Print("open log file err",err)
}else{
log.Out = files
}
logrus.SetOutput(files)
logrus.SetLevel(level)
return
}
這裡日誌檔案我是根據自己的需求,每天一個日誌檔案,可以根據自己的習慣應用去設定日誌的生成;
日誌問價位置配置
config檔案下
config.yaml
log:
dir: /logs/
config.go
package config
import (
"gopkg.in/yaml.v2"
"io/ioutil"
)
var BaseConf Config
type LogConf struct {
Dir string `yaml:"dir"`
}
type Config struct {
Log LogConf `yaml:"log"`
}
func Init() {
confPath := "config/config.yaml"
if yamlFile,err:= ioutil.ReadFile(confPath);err != nil {
panic("read config err:" + err.Error())
}else if err = yaml.Unmarshal(yamlFile,&BaseConf); err != nil{
panic("conf file unmarshal error:"+err.Error())
}
}
這裡配置日誌檔案位置,當然也是可以直接寫的,但是在建議配置在一個檔案中,然後專案啟動是呼叫
r := gin.Default()
//r.Use(middleware.LoggerToFile())
config.Init()
然後就是專案使用
log.Error(logrus.Fields{"err":err.Error(),"source":pkg.GetPath()},"Model - FindArticle - Count")
這其中pkg.GetPath()是獲取當前執行檔案的路徑以及報錯行數
pak方法
package pkg
import (
"runtime"
"strconv"
)
func GetPath() string {
_,path,line,_:= runtime.Caller(1)
response := path +":" + strconv.Itoa(line)
return response
}
後面呈現列印的日誌
至於中介軟體,如果是大型專案多臺伺服器,使用更好,我這沒必要也就沒寫入,下面直接放中介軟體程式碼:
package middleware
import (
"bytes"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
"go_service/log"
"io/ioutil"
"time"
)
func LoggerToFile() gin.HandlerFunc {
return func(ctx *gin.Context) {
//開始時間
start := time.Now()
//請求報文
var resquestBody []byte
if ctx.Request.Body != nil{
var err error
resquestBody,err = ctx.GetRawData()
if err != nil {
log.Warn(logrus.Fields{"err":err.Error()},"get http request")
}
ctx.Request.Body = ioutil.NopCloser(bytes.NewBuffer(resquestBody))
}
//處理請求
ctx.Next()
//結束時間
end := time.Now()
log.Info(map[string]interface{}{
"statsCode":ctx.Writer.Status(),
"cost":float64(end.Sub(start).Nanoseconds()/1e4)/100.0,
"clientlp":ctx.ClientIP(),
"method":ctx.Request.Method,
"url":ctx.Request.RequestURI,
})
}
}
在啟動專案時使用
r := gin.Default()
r.Use(middleware.LoggerToFile())
列印日誌:
肯定有更好的方法,但是自己沒研究出來,就先使用的現在的封裝
本文連線:點選
博主個人小部落格:嘿嘿