logger.go 2.2 KB

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