serverLogs.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package logs
  2. import (
  3. "github.com/gogf/gf/v2/os/glog"
  4. "log"
  5. )
  6. type commonLogConfig struct {
  7. Path string //系统日志默认文件默认报错路径。默认为./logs
  8. Debug bool //是否打印调试信息。默认false
  9. Stdout bool //是否输出到控制台。默认false
  10. }
  11. func initBaseLog(c *commonLogConfig, fileName string) (l *glog.Logger) {
  12. l = glog.New()
  13. _ = l.SetPath(c.Path)
  14. l.SetFile(fileName)
  15. l.SetDebug(c.Debug)
  16. l.SetStdoutPrint(c.Stdout)
  17. return
  18. }
  19. // 请求记录配置
  20. type serverLogConfig struct {
  21. *commonLogConfig
  22. ServerErrorStack bool //当Server捕获到异常时是否记录堆栈信息到日志中。默认为true
  23. ServerRequestLogSaveDb bool //请求日志是否保存至数据库。默认false
  24. ServerErrorLogEnabled bool //是否记录访问异常日志到日志中。默认为true
  25. ServerErrorLogPattern string //访问异常日志文件格式。默认为"error-{Ymd}.log"
  26. ServerAccessLogEnabled bool //是否记录访问日志。默认为false
  27. ServerAccessLogPattern string //记录访问日志文件格式。默认为"access-{Ymd}.log"
  28. ServerRequestTimeout int64
  29. }
  30. // server 请求日志
  31. type serverLog struct {
  32. accessLog, errorLog *glog.Logger
  33. Config serverLogConfig
  34. Notice *Notice
  35. }
  36. func initServerLog(sc serverLogConfig, nc NoticeConfig) *serverLog {
  37. accessLog, errorLog := glog.New(), glog.New()
  38. _ = accessLog.SetPath(sc.Path)
  39. _ = errorLog.SetPath(sc.Path)
  40. accessLog.SetFile(sc.ServerAccessLogPattern)
  41. errorLog.SetFile(sc.ServerErrorLogPattern)
  42. accessLog.SetDebug(sc.Debug)
  43. errorLog.SetDebug(sc.Debug)
  44. accessLog.SetStdoutPrint(sc.Stdout)
  45. errorLog.SetStdoutPrint(sc.Stdout)
  46. notice, err := newNotice(nc)
  47. if err != nil {
  48. log.Println("GNotice nsq通知初始化异常", err)
  49. }
  50. slog := &serverLog{
  51. accessLog: accessLog,
  52. errorLog: errorLog,
  53. Config: sc,
  54. Notice: notice,
  55. }
  56. if sc.ServerRequestLogSaveDb {
  57. go slog.SaveLogTask()
  58. }
  59. return slog
  60. }