logs.go 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. package utils
  2. import (
  3. "github.com/sirupsen/logrus"
  4. "gopkg.in/natefinch/lumberjack.v2"
  5. "os"
  6. "path"
  7. )
  8. const (
  9. DefaultLogPath = "./rdlucklog"
  10. DefaultBinlogPath = "./binlog"
  11. DefaultBinlogFile = "binlog.log"
  12. )
  13. var FileLog = logrus.New()
  14. var Binlog = logrus.New()
  15. var ApiLog = logrus.New()
  16. func init() {
  17. logPath := LogPath
  18. if logPath == "" {
  19. logPath = DefaultLogPath
  20. }
  21. logFile := LogFile
  22. if logFile == "" {
  23. logFile = "eta_chart_lib.log"
  24. }
  25. os.MkdirAll(logPath, os.ModePerm)
  26. // 打开文件
  27. logFileName := path.Join(logPath, logFile)
  28. // 使用滚动压缩方式记录日志
  29. rolling(FileLog, logFileName)
  30. //rolling(bLogFileName)
  31. // 设置日志输出JSON格式
  32. jsonFormat := new(logrus.JSONFormatter)
  33. jsonFormat.DisableHTMLEscape = true
  34. FileLog.SetFormatter(jsonFormat)
  35. FileLog.SetReportCaller(true)
  36. //LogInstance.SetFormatter(&logrus.TextFormatter{})
  37. // 设置日志记录级别
  38. //FileLog.SetLevel(logrus.DebugLevel)
  39. //FileLog.Info("abc")
  40. initBinlog()
  41. initApiLog()
  42. }
  43. func initBinlog() {
  44. //binlog日志
  45. binlogPath := BinLogPath
  46. if binlogPath == "" {
  47. binlogPath = DefaultBinlogPath
  48. }
  49. binlogFile := BinLogFile
  50. if binlogFile == "" {
  51. binlogFile = DefaultBinlogFile
  52. }
  53. os.MkdirAll(binlogPath, os.ModePerm)
  54. // 使用滚动压缩方式记录日志
  55. logFileName := path.Join(binlogPath, binlogFile)
  56. rolling(Binlog, logFileName)
  57. //rolling(bLogFileName)
  58. // 设置日志输出JSON格式
  59. jsonFormat := new(logrus.JSONFormatter)
  60. jsonFormat.DisableHTMLEscape = true
  61. Binlog.SetFormatter(jsonFormat)
  62. }
  63. func initApiLog() {
  64. logPath := ApiLogPath
  65. if logPath == "" {
  66. if RunMode == "release" {
  67. logPath = `/data/rdlucklog/eta_chart_lib`
  68. } else {
  69. logPath = `./rdlucklog/api`
  70. }
  71. }
  72. logFile := ApiLogFile
  73. if logFile == "" {
  74. logFile = "eta_chart_lib_api.log"
  75. }
  76. os.MkdirAll(logPath, os.ModePerm)
  77. // 打开文件
  78. logFileName := path.Join(logPath, logFile)
  79. // 使用滚动压缩方式记录日志
  80. rolling(ApiLog, logFileName)
  81. //rolling(bLogFileName)
  82. // 设置日志输出JSON格式
  83. jsonFormat := new(logrus.JSONFormatter)
  84. jsonFormat.DisableHTMLEscape = true
  85. ApiLog.SetFormatter(jsonFormat)
  86. }
  87. // 日志滚动设置
  88. func rolling(fLog *logrus.Logger, logFile string) {
  89. // 设置输出
  90. fLog.SetOutput(&lumberjack.Logger{
  91. Filename: logFile, //日志文件位置
  92. MaxSize: 500, // 单文件最大容量,单位是MB
  93. MaxBackups: 3, // 最大保留过期文件个数
  94. MaxAge: 7, // 保留过期文件的最大时间间隔,单位是天
  95. Compress: true, // 是否需要压缩滚动日志, 使用的 gzip 压缩
  96. })
  97. }