logger.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package gin
  2. import (
  3. "fmt"
  4. "log"
  5. "os"
  6. "time"
  7. )
  8. func ErrorLogger() HandlerFunc {
  9. return func(c *Context) {
  10. c.Next()
  11. if len(c.Errors) > 0 {
  12. // -1 status code = do not change current one
  13. c.JSON(-1, c.Errors)
  14. }
  15. }
  16. }
  17. var (
  18. green = string([]byte{27, 91, 57, 55, 59, 52, 50, 109})
  19. white = string([]byte{27, 91, 57, 48, 59, 52, 55, 109})
  20. yellow = string([]byte{27, 91, 57, 55, 59, 52, 51, 109})
  21. red = string([]byte{27, 91, 57, 55, 59, 52, 49, 109})
  22. reset = string([]byte{27, 91, 48, 109})
  23. )
  24. func Logger() HandlerFunc {
  25. logger := log.New(os.Stdout, "", 0)
  26. return func(c *Context) {
  27. // Start timer
  28. start := time.Now()
  29. // Process request
  30. c.Next()
  31. var color string
  32. code := c.Writer.Status()
  33. switch {
  34. case code >= 200 && code <= 299:
  35. color = green
  36. case code >= 300 && code <= 399:
  37. color = white
  38. case code >= 400 && code <= 499:
  39. color = yellow
  40. default:
  41. color = red
  42. }
  43. latency := time.Since(start)
  44. logger.Printf("[GIN] %v |%s %3d %s| %12v | %3s %s\n",
  45. time.Now().Format("2006/01/02 - 15:04:05"),
  46. color, c.Writer.Status(), reset,
  47. latency,
  48. c.Req.Method, c.Req.URL.Path,
  49. )
  50. // Calculate resolution time
  51. if len(c.Errors) > 0 {
  52. fmt.Println(c.Errors.String())
  53. }
  54. }
  55. }