logs.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package utils
  2. import (
  3. "encoding/json"
  4. "github.com/beego/beego/v2/core/logs"
  5. "os"
  6. "path"
  7. )
  8. const (
  9. DefaultLogPath = "./etalogs/filelog"
  10. DefaultBinlogPath = "./etalogs/binlog"
  11. )
  12. var FileLog *logs.BeeLogger
  13. var Binlog *logs.BeeLogger
  14. func init() {
  15. if LogMaxDays == 0 {
  16. LogMaxDays = 30
  17. }
  18. logPath := LogPath
  19. if logPath == "" {
  20. logPath = DefaultLogPath
  21. }
  22. logFile := LogFile
  23. if logFile == "" {
  24. logFile = "filelog.log"
  25. }
  26. os.MkdirAll(logPath, os.ModePerm)
  27. // 打开文件
  28. logFileName := path.Join(logPath, logFile)
  29. FileLog = logs.NewLogger(1000000)
  30. logConf := getDefaultLogConfig()
  31. logConf.FileName = logFileName
  32. b, _ := json.Marshal(logConf)
  33. FileLog.SetLogger(logs.AdapterFile, string(b))
  34. FileLog.EnableFuncCallDepth(true)
  35. initBinlog()
  36. }
  37. type logConfig struct {
  38. FileName string `json:"filename" description:"保存的文件名"`
  39. MaxLines int `json:"maxlines" description:"每个文件保存的最大行数,默认值 1000000"`
  40. MaxSize int `json:"maxsize" description:"每个文件保存的最大尺寸,默认值是 1 << 28, //256 MB"`
  41. Daily bool `json:"daily" description:"是否按照每天 logrotate,默认是 true"`
  42. MaxDays int `json:"maxdays" description:"文件最多保存多少天,默认保存 7 天"`
  43. Rotate bool `json:"rotate" description:"是否开启 logrotate,默认是 true"`
  44. Level int `json:"level" description:"日志保存的时候的级别,默认是 Trace 级别"`
  45. Color bool `json:"color" description:"日志是否输出颜色"`
  46. //Perm string `json:"perm" description:"日志文件权限"`
  47. }
  48. func initBinlog() {
  49. //binlog日志
  50. //binlog日志
  51. binlogPath := BinLogPath
  52. if binlogPath == "" {
  53. binlogPath = DefaultBinlogPath
  54. }
  55. binlogFile := BinLogFile
  56. if binlogFile == "" {
  57. binlogFile = "binlog.log"
  58. }
  59. os.MkdirAll(binlogPath, os.ModePerm)
  60. logFileName := path.Join(binlogPath, binlogFile)
  61. Binlog = logs.NewLogger(1000000)
  62. logConf := getDefaultLogConfig()
  63. logConf.FileName = logFileName
  64. //logConf.MaxLines = 10000000
  65. //logConf.Rotate = true
  66. b, _ := json.Marshal(logConf)
  67. Binlog.SetLogger(logs.AdapterFile, string(b))
  68. Binlog.EnableFuncCallDepth(true)
  69. }
  70. func getDefaultLogConfig() logConfig {
  71. return logConfig{
  72. FileName: "",
  73. MaxLines: 10000000,
  74. MaxSize: 1 << 28,
  75. Daily: true,
  76. MaxDays: LogMaxDays, //我就是喜欢31天,咋滴,不喜欢你就自己改-_-!
  77. Rotate: true,
  78. Level: logs.LevelTrace,
  79. //Perm: "",
  80. }
  81. }