log.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. package core
  2. import (
  3. "eta_gn/eta_obs/config"
  4. "eta_gn/eta_obs/global"
  5. "eta_gn/eta_obs/utils"
  6. "fmt"
  7. "github.com/gin-gonic/gin"
  8. rotatelogs "github.com/lestrrat-go/file-rotatelogs"
  9. oplogging "github.com/op/go-logging"
  10. "io"
  11. "os"
  12. "strings"
  13. "time"
  14. )
  15. const (
  16. Module = "eta_obs"
  17. )
  18. var (
  19. defaultFormatter = ` %{time:2006/01/02 - 15:04:05.000} %{longfile} %{color:bold}▶ [%{level:.6s}] %{message}%{color:reset}`
  20. )
  21. // 初始化日志
  22. func init() {
  23. gin.SetMode(global.CONFIG.Serve.RunMode)
  24. logConfig := global.CONFIG.Log
  25. logger := oplogging.MustGetLogger(Module)
  26. var backends []oplogging.Backend
  27. //注册输出
  28. registerStdout(logConfig, &backends)
  29. //注册框架输出(日志文件)
  30. logWriter := registerFile(logConfig, &backends, logConfig.LogDirPath, logConfig.LogSoftLink)
  31. if logWriter != nil {
  32. if global.CONFIG.Serve.RunMode == "debug" {
  33. gin.DefaultWriter = io.MultiWriter(logWriter, os.Stdout)
  34. } else {
  35. gin.DefaultWriter = io.MultiWriter(logWriter)
  36. }
  37. }
  38. oplogging.SetBackend(backends...)
  39. global.LOG = logger
  40. // 初始化自定义输出的日志
  41. initFileLog()
  42. }
  43. // initFileLog 初始化自定义日志
  44. func initFileLog() {
  45. logConfig := global.CONFIG.Log
  46. // 没有单独配置的话,那就走默认的日志输出
  47. if logConfig.FilelogDirPath == "" || logConfig.FilelogSoftLink == `` {
  48. global.FILE_LOG = global.LOG
  49. return
  50. }
  51. logger := oplogging.MustGetLogger(Module)
  52. var backends []oplogging.Backend
  53. //注册控制台输出
  54. //registerStdout(logConfig, &backends)
  55. // 注册文件输出(日志文件)
  56. _ = registerFile(logConfig, &backends, logConfig.FilelogDirPath, logConfig.FilelogSoftLink)
  57. defaultBackend := oplogging.AddModuleLevel(backends[0])
  58. logger.SetBackend(defaultBackend)
  59. global.FILE_LOG = logger
  60. }
  61. func registerStdout(c config.Log, backends *[]oplogging.Backend) {
  62. if c.Stdout != "" {
  63. level, err := oplogging.LogLevel(c.Stdout)
  64. if err != nil {
  65. fmt.Println(err)
  66. }
  67. *backends = append(*backends, createBackend(os.Stdout, c, level))
  68. }
  69. }
  70. // registerFile 注册文件日志
  71. func registerFile(c config.Log, backends *[]oplogging.Backend, logDir, logSoftLink string) io.Writer {
  72. if c.FileStdout != "" {
  73. if ok, _ := utils.PathExists(logDir); !ok {
  74. // directory not exist
  75. fmt.Println("create log directory")
  76. _ = os.Mkdir(logDir, os.ModePerm)
  77. }
  78. //日志保留时间
  79. saveMaxTime := time.Duration(global.CONFIG.Log.SaveMaxDay) * 24 * time.Hour
  80. //日志切割时间(每隔多久切割一次)
  81. cuttingTime := time.Duration(global.CONFIG.Log.CuttingDay) * 24 * time.Hour
  82. //使用rotatelogs
  83. fileWriter, err := rotatelogs.New(
  84. logDir+string(os.PathSeparator)+"%Y-%m-%d-%H-%M.log",
  85. // 生成软链,指向最新日志文件
  86. rotatelogs.WithLinkName(logSoftLink),
  87. // 以下两个配置不能同时设置,一个是保留天数,一个是保留分拣份数
  88. rotatelogs.WithMaxAge(saveMaxTime), //日志保留多久,最小分钟为单位
  89. //rotatelogs.WithRotationCount(5), //number 默认7份 大于7份 或到了清理时间 开始清理
  90. // time period of log file switching
  91. rotatelogs.WithRotationTime(cuttingTime), //rotate 最小为1分钟轮询。默认60s 低于1分钟就按1分钟来
  92. )
  93. if err != nil {
  94. fmt.Println(err)
  95. }
  96. level, err := oplogging.LogLevel(c.FileStdout)
  97. if err != nil {
  98. fmt.Println(err)
  99. }
  100. *backends = append(*backends, createBackend(fileWriter, c, level))
  101. return fileWriter
  102. }
  103. return nil
  104. }
  105. // createBackend 创建一个新的日志记录器
  106. func createBackend(w io.Writer, c config.Log, level oplogging.Level) oplogging.Backend {
  107. backend := oplogging.NewLogBackend(w, c.Prefix, 0)
  108. stdoutWriter := false
  109. if w == os.Stdout {
  110. stdoutWriter = true
  111. }
  112. format := getLogFormatter(c, stdoutWriter)
  113. backendLeveled := oplogging.AddModuleLevel(oplogging.NewBackendFormatter(backend, format))
  114. backendLeveled.SetLevel(level, Module)
  115. return backendLeveled
  116. }
  117. func getLogFormatter(c config.Log, stdoutWriter bool) oplogging.Formatter {
  118. pattern := defaultFormatter
  119. if !stdoutWriter {
  120. // Color is only required for console output
  121. // Other writers don't need %{color} tag
  122. pattern = strings.Replace(pattern, "%{color:bold}", "", -1)
  123. pattern = strings.Replace(pattern, "%{color:reset}", "", -1)
  124. }
  125. if !c.LogFile {
  126. // Remove %{logfile} tag
  127. pattern = strings.Replace(pattern, "%{longfile}", "", -1)
  128. }
  129. return oplogging.MustStringFormatter(pattern)
  130. }