[技術分享]日誌切割(按天切割日誌)

蕭風發表於2020-08-14

使用 logrusgo-file-rotatelogs 按天切割日誌,原始碼: iris-framework

package config

import (
    config "IrisFramework/config/Log"
    rotatelogs "github.com/lestrrat/go-file-rotatelogs"
    "github.com/rifflock/lfshook"
    "github.com/sirupsen/logrus"
    "os"
    "path"
    "time"
)

const LogPath = "./storage/logs"
const FileSuffix = ".log"

var Log = logrus.New()

func InitLog() {
    Log.Out = os.Stdout
    var loglevel logrus.Level
    err := loglevel.UnmarshalText([]byte("info"))
    if err != nil {
        Log.Panicf("設定log級別失敗:%v", err)
    }

    Log.SetLevel(loglevel)

    NewSimpleLogger(Log, LogPath, 8)
}

/**
  檔案日誌
*/
func NewSimpleLogger(log *logrus.Logger, logPath string, save uint) {

    lfHook := lfshook.NewHook(lfshook.WriterMap{
        logrus.DebugLevel: writer(logPath, "debug", save), // 為不同級別設定不同的輸出目的
        logrus.InfoLevel:  writer(logPath, "info", save),
        logrus.WarnLevel:  writer(logPath, "warn", save),
        logrus.ErrorLevel: writer(logPath, "error", save),
        logrus.FatalLevel: writer(logPath, "fatal", save),
        logrus.PanicLevel: writer(logPath, "panic", save),
    }, &config.MineFormatter{})

    log.AddHook(lfHook)
}

/**
檔案設定
*/
func writer(logPath string, level string, save uint) *rotatelogs.RotateLogs {
    logFullPath := path.Join(logPath, level)
    var cstSh, _ = time.LoadLocation("Asia/Shanghai") //上海
    fileSuffix := time.Now().In(cstSh).Format("2006-01-02") + FileSuffix

    logier, err := rotatelogs.New(
        logFullPath+"-"+fileSuffix,
        rotatelogs.WithLinkName(logFullPath),      // 生成軟鏈,指向最新日誌檔案
        rotatelogs.WithRotationCount(int(save)),   // 檔案最大儲存份數
        rotatelogs.WithRotationTime(time.Hour*24), // 日誌切割時間間隔
    )

    if err != nil {
        panic(err)
    }
    return logier
}

自定義日誌輸出格式

package config

import (
    "fmt"
    "github.com/sirupsen/logrus"
    "strings"
    "time"
)

type MineFormatter struct{}

const TimeFormat = "2006-01-02 15:04:05"

func (s *MineFormatter) Format(entry *logrus.Entry) ([]byte, error) {

    msg := fmt.Sprintf("[%s] [%s] %s\n", time.Now().Local().Format(TimeFormat), strings.ToUpper(entry.Level.String()), entry.Message)

    return []byte(msg), nil
}

列印輸出如下:

[2020-08-05 11:34:08] [INFO] [gorm] [sql] [1.604712ms] SELECT * FROM `user`  WHERE `user`.`deleted_at` IS NULL AND ((username like ?)) []interface {}{"%風%"} 

【技術分享】日誌切割(按天切割日誌)

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章