ghttp_server_log.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. package ghttp
  7. import (
  8. "fmt"
  9. "github.com/gogf/gf/errors/gerror"
  10. "github.com/gogf/gf/os/glog"
  11. )
  12. // Logger returns the logger of the server.
  13. func (s *Server) Logger() *glog.Logger {
  14. return s.config.Logger
  15. }
  16. // handleAccessLog handles the access logging for server.
  17. func (s *Server) handleAccessLog(r *Request) {
  18. if !s.IsAccessLogEnabled() {
  19. return
  20. }
  21. scheme := "http"
  22. if r.TLS != nil {
  23. scheme = "https"
  24. }
  25. s.Logger().File(s.config.AccessLogPattern).
  26. Stdout(s.config.LogStdout).
  27. Printf(
  28. `%d "%s %s %s %s %s" %.3f, %s, "%s", "%s"`,
  29. r.Response.Status,
  30. r.Method, scheme, r.Host, r.URL.String(), r.Proto,
  31. float64(r.LeaveTime-r.EnterTime)/1000,
  32. r.GetClientIp(), r.Referer(), r.UserAgent(),
  33. )
  34. }
  35. // handleErrorLog handles the error logging for server.
  36. func (s *Server) handleErrorLog(err error, r *Request) {
  37. // It does nothing if error logging is custom disabled.
  38. if !s.IsErrorLogEnabled() {
  39. return
  40. }
  41. scheme := "http"
  42. if r.TLS != nil {
  43. scheme = "https"
  44. }
  45. content := fmt.Sprintf(
  46. `%d "%s %s %s %s %s" %.3f, %s, "%s", "%s"`,
  47. r.Response.Status, r.Method, scheme, r.Host, r.URL.String(), r.Proto,
  48. float64(r.LeaveTime-r.EnterTime)/1000,
  49. r.GetClientIp(), r.Referer(), r.UserAgent(),
  50. )
  51. if s.config.ErrorStack {
  52. if stack := gerror.Stack(err); stack != "" {
  53. content += "\nStack:\n" + stack
  54. } else {
  55. content += ", " + err.Error()
  56. }
  57. } else {
  58. content += ", " + err.Error()
  59. }
  60. s.config.Logger.
  61. File(s.config.ErrorLogPattern).
  62. Stdout(s.config.LogStdout).
  63. Print(content)
  64. }