From f66c09e59d1c38e0297bb3be82ef541c4c966af9 Mon Sep 17 00:00:00 2001 From: wyhwyhwyh <573805736@qq.com> Date: Wed, 18 Aug 2021 11:01:45 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9Elogger?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- go.mod | 3 +++ logger.go | 58 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ main.go | 4 ++++ 3 files changed, 65 insertions(+) create mode 100644 logger.go diff --git a/go.mod b/go.mod index 5b6501f..02cb7b9 100644 --- a/go.mod +++ b/go.mod @@ -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 ) diff --git a/logger.go b/logger.go new file mode 100644 index 0000000..991dc8f --- /dev/null +++ b/logger.go @@ -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 +} diff --git a/main.go b/main.go index 34c468a..30a8b20 100644 --- a/main.go +++ b/main.go @@ -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()