新增logger

This commit is contained in:
wyh 2021-08-18 11:01:45 +08:00
parent 64dda2f8e0
commit f66c09e59d
3 changed files with 65 additions and 0 deletions

3
go.mod
View File

@ -4,6 +4,9 @@ go 1.16
require (
github.com/gin-gonic/gin v1.7.4
github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible // indirect
github.com/lestrrat-go/strftime v1.0.5 // indirect
github.com/rifflock/lfshook v0.0.0-20180920164130-b9218ef580f5 // indirect
github.com/sirupsen/logrus v1.8.1
github.com/spf13/viper v1.8.1
)

58
logger.go Normal file
View File

@ -0,0 +1,58 @@
package main
import (
"fmt"
"os"
"time"
rotatelogs "github.com/lestrrat-go/file-rotatelogs"
"github.com/rifflock/lfshook"
log "github.com/sirupsen/logrus"
)
func init() {
//日志初始化
//log.SetOutput(os.Stdout)
log.SetLevel(log.DebugLevel)
log.AddHook(newLfsHook(72))
}
func newLfsHook(maxRemainCnt uint) log.Hook {
//检查与创建日志文件夹
_, err := os.Stat("logs")
if os.IsNotExist(err) {
os.Mkdir("logs", 0755)
}
logName := fmt.Sprintf(`logs/%s`, APPNAME)
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())
}
log.SetLevel(log.DebugLevel)
lfsHook := lfshook.NewHook(lfshook.WriterMap{
log.DebugLevel: writer,
log.InfoLevel: writer,
log.WarnLevel: writer,
log.ErrorLevel: writer,
log.FatalLevel: writer,
log.PanicLevel: writer,
}, &log.TextFormatter{DisableColors: true})
return lfsHook
}

View File

@ -8,6 +8,10 @@ import (
"github.com/spf13/viper"
)
const (
APPNAME = "srv-ijustjump"
)
func main() {
cf := flag.String("config", "config.yaml", "file of config")
flag.Parse()