logger.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  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. "fmt"
  7. "io"
  8. "time"
  9. )
  10. var (
  11. green = string([]byte{27, 91, 57, 55, 59, 52, 50, 109})
  12. white = string([]byte{27, 91, 57, 48, 59, 52, 55, 109})
  13. yellow = string([]byte{27, 91, 57, 55, 59, 52, 51, 109})
  14. red = string([]byte{27, 91, 57, 55, 59, 52, 49, 109})
  15. blue = string([]byte{27, 91, 57, 55, 59, 52, 52, 109})
  16. magenta = string([]byte{27, 91, 57, 55, 59, 52, 53, 109})
  17. cyan = string([]byte{27, 91, 57, 55, 59, 52, 54, 109})
  18. reset = string([]byte{27, 91, 48, 109})
  19. )
  20. func ErrorLogger() HandlerFunc {
  21. return ErrorLoggerT(ErrorTypeAll)
  22. }
  23. func ErrorLoggerT(typ uint32) HandlerFunc {
  24. return func(c *Context) {
  25. c.Next()
  26. errs := c.Errors.ByType(typ)
  27. if len(errs) > 0 {
  28. // -1 status code = do not change current one
  29. c.JSON(-1, c.Errors)
  30. }
  31. }
  32. }
  33. func Logger() HandlerFunc {
  34. return LoggerInFile(DefaultLogFile)
  35. }
  36. func LoggerInFile(out io.Writer) HandlerFunc {
  37. return func(c *Context) {
  38. // Start timer
  39. start := time.Now()
  40. // Process request
  41. c.Next()
  42. // Stop timer
  43. end := time.Now()
  44. latency := end.Sub(start)
  45. clientIP := c.ClientIP()
  46. method := c.Request.Method
  47. statusCode := c.Writer.Status()
  48. statusColor := colorForStatus(statusCode)
  49. methodColor := colorForMethod(method)
  50. comment := c.Errors.String()
  51. fmt.Fprintf(out, "[GIN] %v |%s %3d %s| %12v | %s |%s %s %-7s %s\n%s",
  52. end.Format("2006/01/02 - 15:04:05"),
  53. statusColor, statusCode, reset,
  54. latency,
  55. clientIP,
  56. methodColor, reset, method,
  57. c.Request.URL.Path,
  58. comment,
  59. )
  60. }
  61. }
  62. func colorForStatus(code int) string {
  63. switch {
  64. case code >= 200 && code <= 299:
  65. return green
  66. case code >= 300 && code <= 399:
  67. return white
  68. case code >= 400 && code <= 499:
  69. return yellow
  70. default:
  71. return red
  72. }
  73. }
  74. func colorForMethod(method string) string {
  75. switch {
  76. case method == "GET":
  77. return blue
  78. case method == "POST":
  79. return cyan
  80. case method == "PUT":
  81. return yellow
  82. case method == "DELETE":
  83. return red
  84. case method == "PATCH":
  85. return green
  86. case method == "HEAD":
  87. return magenta
  88. case method == "OPTIONS":
  89. return white
  90. default:
  91. return reset
  92. }
  93. }