logrus的使用及格式定製

點點2B發表於2020-10-21

在查詢許多資料後,整理了以下程式碼:

package config

import (
	"fmt"
	nested "github.com/antonfisher/nested-logrus-formatter"
	"github.com/lestrrat-go/file-rotatelogs"
	"github.com/rifflock/lfshook"
	"github.com/sirupsen/logrus"
	"path/filepath"
	"runtime"
	"time"
)

var (
	Log *logrus.Logger
)

func InitLogger() {
	Log = logrus.New()
	hook := NewLfsHook(filepath.Join(Cf.Logger.Path, "pack"), 0, 5)
	Log.AddHook(hook)
	Log.SetFormatter(formatter(true))
	Log.SetReportCaller(true)
}

func formatter(isConsole bool) *nested.Formatter {
	fmtter := &nested.Formatter{
		HideKeys:        true,
		TimestampFormat: "2006-01-02 15:04:05",
		CallerFirst:     true,
		CustomCallerFormatter: func(frame *runtime.Frame) string {
			funcInfo := runtime.FuncForPC(frame.PC)
			if funcInfo == nil {
				return "error during runtime.FuncForPC"
			}
			fullPath, line := funcInfo.FileLine(frame.PC)
			return fmt.Sprintf(" [%v:%v]", filepath.Base(fullPath), line)
		},
	}
	if isConsole {
		fmtter.NoColors = false
	} else {
		fmtter.NoColors = true
	}
	return fmtter
}

func NewLfsHook(logName string, rotationTime time.Duration, leastDay uint) logrus.Hook {
	writer, err := rotatelogs.New(
		// 日誌檔案
		logName+".%Y%m%d%H%M%S",
		// 日誌週期(預設每86400秒/一天旋轉一次)
		//rotatelogs.WithRotationTime(rotationTime),
		// 清除歷史 (WithMaxAge和WithRotationCount只能選其一)
		//rotatelogs.WithMaxAge(time.Hour*24*7), //預設每7天清除下日誌檔案
		rotatelogs.WithRotationCount(leastDay), //只保留最近的N個日誌檔案
	)
	if err != nil {
		panic(err)
	}

	// 可設定按不同level建立不同的檔名
	lfsHook := lfshook.NewHook(lfshook.WriterMap{
		logrus.DebugLevel: writer,
		logrus.InfoLevel:  writer,
		logrus.WarnLevel:  writer,
		logrus.ErrorLevel: writer,
		logrus.FatalLevel: writer,
		logrus.PanicLevel: writer,
		//}, &logrus.JSONFormatter{TimestampFormat: "2006-01-02 15:04:05"})
	}, formatter(false))

	return lfsHook
}

終端輸出樣式:
終端輸出樣式

日誌檔案輸出樣式:
日誌檔案輸出樣式

相關文章