75 lines
1.8 KiB
Go
75 lines
1.8 KiB
Go
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.InfoLevel)
|
||
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`, "device-wg")
|
||
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())
|
||
}
|
||
|
||
level := os.Getenv("LOGLEVEL")
|
||
|
||
switch level {
|
||
case "debug":
|
||
logrus.SetLevel(logrus.DebugLevel)
|
||
case "info":
|
||
logrus.SetLevel(logrus.InfoLevel)
|
||
case "warn":
|
||
logrus.SetLevel(logrus.WarnLevel)
|
||
case "error":
|
||
logrus.SetLevel(logrus.ErrorLevel)
|
||
case "fatal":
|
||
logrus.SetLevel(logrus.FatalLevel)
|
||
default:
|
||
logrus.SetLevel(logrus.PanicLevel)
|
||
}
|
||
|
||
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
|
||
}
|