ghttp_server_log.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. )
  11. // handleAccessLog handles the access logging for server.
  12. func (s *Server) handleAccessLog(r *Request) {
  13. if !s.IsAccessLogEnabled() {
  14. return
  15. }
  16. scheme := "http"
  17. if r.TLS != nil {
  18. scheme = "https"
  19. }
  20. s.Logger().Ctx(r.Context()).File(s.config.AccessLogPattern).
  21. Stdout(s.config.LogStdout).
  22. Printf(
  23. `%d "%s %s %s %s %s" %.3f, %s, "%s", "%s"`,
  24. r.Response.Status,
  25. r.Method, scheme, r.Host, r.URL.String(), r.Proto,
  26. float64(r.LeaveTime-r.EnterTime)/1000,
  27. r.GetClientIp(), r.Referer(), r.UserAgent(),
  28. )
  29. }
  30. // handleErrorLog handles the error logging for server.
  31. func (s *Server) handleErrorLog(err error, r *Request) {
  32. // It does nothing if error logging is custom disabled.
  33. if !s.IsErrorLogEnabled() {
  34. return
  35. }
  36. scheme := "http"
  37. if r.TLS != nil {
  38. scheme = "https"
  39. }
  40. content := fmt.Sprintf(
  41. `%d "%s %s %s %s %s" %.3f, %s, "%s", "%s"`,
  42. r.Response.Status, r.Method, scheme, r.Host, r.URL.String(), r.Proto,
  43. float64(r.LeaveTime-r.EnterTime)/1000,
  44. r.GetClientIp(), r.Referer(), r.UserAgent(),
  45. )
  46. if s.config.ErrorStack {
  47. if stack := gerror.Stack(err); stack != "" {
  48. content += "\nStack:\n" + stack
  49. } else {
  50. content += ", " + err.Error()
  51. }
  52. } else {
  53. content += ", " + err.Error()
  54. }
  55. s.Logger().Ctx(r.Context()).
  56. File(s.config.ErrorLogPattern).
  57. Stdout(s.config.LogStdout).
  58. Print(content)
  59. }