log.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package initialize
  2. import (
  3. "encoding/json"
  4. "github.com/beego/beego/v2/core/logs"
  5. beego "github.com/beego/beego/v2/server/web"
  6. "log"
  7. )
  8. func init() {
  9. log.SetFlags(log.Lshortfile | log.Ltime | log.Ldate)
  10. log.Println("系统日志初始化...")
  11. maxdays, err := beego.AppConfig.Int("maxdays")
  12. if err != nil {
  13. log.Println("无法获取maxdays:", err)
  14. }
  15. level, err := beego.AppConfig.Int("level")
  16. if err != nil {
  17. log.Println("无法获取level:", err)
  18. }
  19. maxlines, err := beego.AppConfig.Int("maxlines")
  20. if err != nil {
  21. log.Println("无法获取maxlines:", err)
  22. }
  23. dataSource := &struct {
  24. Filename string `json:"filename"`
  25. Level int `json:"level"`
  26. Maxlines int `json:"maxlines"`
  27. Maxsize int `json:"maxsize"`
  28. Daily bool `json:"daily"`
  29. Maxdays int `json:"maxdays"`
  30. Color bool `json:"color"`
  31. }{
  32. Filename: "files/logs/log.log",
  33. Level: level,
  34. Maxlines: maxlines,
  35. Maxsize: 0,
  36. Daily: true,
  37. Maxdays: maxdays,
  38. Color: true,
  39. }
  40. dataSourceBytes, err := json.Marshal(dataSource)
  41. if err != nil {
  42. log.Println("无法创建dataSource:", err)
  43. }
  44. logs.SetLevel(level)
  45. adapter_type, err := beego.AppConfig.Int("adapter_type")
  46. if err != nil {
  47. log.Println("无法获取adapter_type:", err)
  48. }
  49. // 日志输出选择
  50. switch adapter_type {
  51. case 0:
  52. logs.SetLogger(logs.AdapterConsole)
  53. case 1:
  54. logs.Reset()
  55. logs.SetLogger(logs.AdapterFile, string(dataSourceBytes))
  56. case 2:
  57. logs.SetLogger(logs.AdapterFile, string(dataSourceBytes))
  58. default:
  59. logs.SetLogger(logs.AdapterConsole)
  60. }
  61. // 是否记录日志的调用层级 默认是logs.SetLogFuncCallDepth(2)
  62. logs.EnableFuncCallDepth(true)
  63. logs.Async()
  64. log.Println("系统日志初始化完成")
  65. }