logs.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. logFileName := path.Join(logPath, logFile)
  28. FileLog = logs.NewLogger(1000000)
  29. logConf := getDefaultLogConfig()
  30. logConf.FileName = logFileName
  31. b, _ := json.Marshal(logConf)
  32. FileLog.SetLogger(logs.AdapterFile, string(b))
  33. FileLog.EnableFuncCallDepth(true)
  34. initBinlog()
  35. }
  36. type logConfig struct {
  37. FileName string `json:"filename" description:"保存的文件名"`
  38. MaxLines int `json:"maxlines" description:"每个文件保存的最大行数,默认值 1000000"`
  39. MaxSize int `json:"maxsize" description:"每个文件保存的最大尺寸,默认值是 1 << 28, //256 MB"`
  40. Daily bool `json:"daily" description:"是否按照每天 logrotate,默认是 true"`
  41. MaxDays int `json:"maxdays" description:"文件最多保存多少天,默认保存 7 天"`
  42. Rotate bool `json:"rotate" description:"是否开启 logrotate,默认是 true"`
  43. Level int `json:"level" description:"日志保存的时候的级别,默认是 Trace 级别"`
  44. Color bool `json:"color" description:"日志是否输出颜色"`
  45. }
  46. func initBinlog() {
  47. binlogPath := BinLogPath
  48. if binlogPath == "" {
  49. binlogPath = DefaultBinlogPath
  50. }
  51. binlogFile := BinLogFile
  52. if binlogFile == "" {
  53. binlogFile = "binlog.log"
  54. }
  55. os.MkdirAll(binlogPath, os.ModePerm)
  56. logFileName := path.Join(binlogPath, binlogFile)
  57. Binlog = logs.NewLogger(1000000)
  58. logConf := getDefaultLogConfig()
  59. logConf.FileName = logFileName
  60. b, _ := json.Marshal(logConf)
  61. Binlog.SetLogger(logs.AdapterFile, string(b))
  62. Binlog.EnableFuncCallDepth(true)
  63. }
  64. func getDefaultLogConfig() logConfig {
  65. return logConfig{
  66. FileName: "",
  67. MaxLines: 10000000,
  68. MaxSize: 1 << 28,
  69. Daily: true,
  70. MaxDays: LogMaxDays, //我就是喜欢31天,咋滴,不喜欢你就自己改-_-!
  71. Rotate: true,
  72. Level: logs.LevelTrace,
  73. }
  74. }