logger.go 1.9 KB

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