log.go 4.0 KB

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