logger.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package gin
  2. import (
  3. "log"
  4. "os"
  5. "time"
  6. )
  7. func ErrorLogger() HandlerFunc {
  8. return ErrorLoggerT(ErrorTypeAll)
  9. }
  10. func ErrorLoggerT(typ uint32) HandlerFunc {
  11. return func(c *Context) {
  12. c.Next()
  13. errs := c.Errors.ByType(typ)
  14. if len(errs) > 0 {
  15. // -1 status code = do not change current one
  16. c.JSON(-1, c.Errors)
  17. }
  18. }
  19. }
  20. var (
  21. green = string([]byte{27, 91, 57, 55, 59, 52, 50, 109})
  22. white = string([]byte{27, 91, 57, 48, 59, 52, 55, 109})
  23. yellow = string([]byte{27, 91, 57, 55, 59, 52, 51, 109})
  24. red = string([]byte{27, 91, 57, 55, 59, 52, 49, 109})
  25. reset = string([]byte{27, 91, 48, 109})
  26. )
  27. func Logger() HandlerFunc {
  28. stdlogger := log.New(os.Stdout, "", 0)
  29. //errlogger := log.New(os.Stderr, "", 0)
  30. return func(c *Context) {
  31. // Start timer
  32. start := time.Now()
  33. // Process request
  34. c.Next()
  35. // save the IP of the requester
  36. requester := c.Req.Header.Get("X-Real-IP")
  37. // if the requester-header is empty, check the forwarded-header
  38. if requester == "" {
  39. requester = c.Req.Header.Get("X-Forwarded-For")
  40. }
  41. // if the requester is still empty, use the hard-coded address from the socket
  42. if requester == "" {
  43. requester = c.Req.RemoteAddr
  44. }
  45. var color string
  46. code := c.Writer.Status()
  47. switch {
  48. case code >= 200 && code <= 299:
  49. color = green
  50. case code >= 300 && code <= 399:
  51. color = white
  52. case code >= 400 && code <= 499:
  53. color = yellow
  54. default:
  55. color = red
  56. }
  57. end := time.Now()
  58. latency := end.Sub(start)
  59. stdlogger.Printf("[GIN] %v |%s %3d %s| %12v | %s %4s %s\n",
  60. end.Format("2006/01/02 - 15:04:05"),
  61. color, c.Writer.Status(), reset,
  62. latency,
  63. requester,
  64. c.Req.Method, c.Req.URL.Path,
  65. )
  66. // Calculate resolution time
  67. if len(c.Errors) > 0 {
  68. stdlogger.Println(c.Errors.String())
  69. }
  70. }
  71. }