mqtt-demo/logger.go

59 lines
1.5 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package main
import (
"fmt"
"os"
"time"
rotatelogs "github.com/lestrrat-go/file-rotatelogs"
"github.com/rifflock/lfshook"
"github.com/sirupsen/logrus"
)
func init() {
//日志初始化
//logrus.SetOutput(os.Stdout)
logrus.SetLevel(logrus.DebugLevel)
logrus.AddHook(newLfsHook(72))
}
func newLfsHook(maxRemainCnt uint) logrus.Hook {
//检查与创建日志文件夹
_, err := os.Stat("logs")
if os.IsNotExist(err) {
os.Mkdir("logs", 0755)
}
logName := fmt.Sprintf(`logs/%s`, "MQTT")
writer, err := rotatelogs.New(
logName+"%Y%m%d.log",
// WithLinkName为最新的日志建立软连接以方便随着找到当前日志文件
rotatelogs.WithLinkName(logName),
// WithRotationTime设置日志分割的时间这里设置为一小时分割一次
rotatelogs.WithRotationTime(24*time.Hour),
// WithMaxAge和WithRotationCount二者只能设置一个
// WithMaxAge设置文件清理前的最长保存时间
// WithRotationCount设置文件清理前最多保存的个数。
//rotatelogs.WithMaxAge(time.Hour*24),
rotatelogs.WithRotationCount(maxRemainCnt),
)
if err != nil {
panic("config local file system for logger error: " + err.Error())
}
logrus.SetLevel(logrus.DebugLevel)
lfsHook := lfshook.NewHook(lfshook.WriterMap{
logrus.DebugLevel: writer,
logrus.InfoLevel: writer,
logrus.WarnLevel: writer,
logrus.ErrorLevel: writer,
logrus.FatalLevel: writer,
logrus.PanicLevel: writer,
}, &logrus.TextFormatter{DisableColors: true})
return lfsHook
}