logger.go 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  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. "os"
  9. "time"
  10. "github.com/mattn/go-isatty"
  11. )
  12. var (
  13. green = string([]byte{27, 91, 57, 55, 59, 52, 50, 109})
  14. white = string([]byte{27, 91, 57, 48, 59, 52, 55, 109})
  15. yellow = string([]byte{27, 91, 57, 55, 59, 52, 51, 109})
  16. red = string([]byte{27, 91, 57, 55, 59, 52, 49, 109})
  17. blue = string([]byte{27, 91, 57, 55, 59, 52, 52, 109})
  18. magenta = string([]byte{27, 91, 57, 55, 59, 52, 53, 109})
  19. cyan = string([]byte{27, 91, 57, 55, 59, 52, 54, 109})
  20. reset = string([]byte{27, 91, 48, 109})
  21. disableColor = false
  22. )
  23. // DisableConsoleColor disables color output in the console.
  24. func DisableConsoleColor() {
  25. disableColor = true
  26. }
  27. // ErrorLogger returns a handlerfunc for any error type.
  28. func ErrorLogger() HandlerFunc {
  29. return ErrorLoggerT(ErrorTypeAny)
  30. }
  31. // ErrorLoggerT returns a handlerfunc for a given error type.
  32. func ErrorLoggerT(typ ErrorType) HandlerFunc {
  33. return func(c *Context) {
  34. c.Next()
  35. errors := c.Errors.ByType(typ)
  36. if len(errors) > 0 {
  37. c.JSON(-1, errors)
  38. }
  39. }
  40. }
  41. // Logger instances a Logger middleware that will write the logs to gin.DefaultWriter.
  42. // By default gin.DefaultWriter = os.Stdout.
  43. func Logger() HandlerFunc {
  44. return LoggerWithWriter(DefaultWriter)
  45. }
  46. // LoggerWithWriter instance a Logger middleware with the specified writter buffer.
  47. // Example: os.Stdout, a file opened in write mode, a socket...
  48. func LoggerWithWriter(out io.Writer, notlogged ...string) HandlerFunc {
  49. isTerm := true
  50. if w, ok := out.(*os.File); !ok ||
  51. (os.Getenv("TERM") == "dumb" || (!isatty.IsTerminal(w.Fd()) && !isatty.IsCygwinTerminal(w.Fd()))) ||
  52. disableColor {
  53. isTerm = false
  54. }
  55. var skip map[string]struct{}
  56. if length := len(notlogged); length > 0 {
  57. skip = make(map[string]struct{}, length)
  58. for _, path := range notlogged {
  59. skip[path] = struct{}{}
  60. }
  61. }
  62. return func(c *Context) {
  63. // Start timer
  64. start := time.Now()
  65. path := c.Request.URL.Path
  66. raw := c.Request.URL.RawQuery
  67. // Process request
  68. c.Next()
  69. // Log only when path is not being skipped
  70. if _, ok := skip[path]; !ok {
  71. // Stop timer
  72. end := time.Now()
  73. latency := end.Sub(start)
  74. clientIP := c.ClientIP()
  75. method := c.Request.Method
  76. statusCode := c.Writer.Status()
  77. var statusColor, methodColor string
  78. if isTerm {
  79. statusColor = colorForStatus(statusCode)
  80. methodColor = colorForMethod(method)
  81. }
  82. comment := c.Errors.ByType(ErrorTypePrivate).String()
  83. if raw != "" {
  84. path = path + "?" + raw
  85. }
  86. fmt.Fprintf(out, "[GIN] %v |%s %3d %s| %13v | %15s |%s %-7s %s %s\n%s",
  87. end.Format("2006/01/02 - 15:04:05"),
  88. statusColor, statusCode, reset,
  89. latency,
  90. clientIP,
  91. methodColor, method, reset,
  92. path,
  93. comment,
  94. )
  95. }
  96. }
  97. }
  98. func colorForStatus(code int) string {
  99. switch {
  100. case code >= 200 && code < 300:
  101. return green
  102. case code >= 300 && code < 400:
  103. return white
  104. case code >= 400 && code < 500:
  105. return yellow
  106. default:
  107. return red
  108. }
  109. }
  110. func colorForMethod(method string) string {
  111. switch method {
  112. case "GET":
  113. return blue
  114. case "POST":
  115. return cyan
  116. case "PUT":
  117. return yellow
  118. case "DELETE":
  119. return red
  120. case "PATCH":
  121. return green
  122. case "HEAD":
  123. return magenta
  124. case "OPTIONS":
  125. return white
  126. default:
  127. return reset
  128. }
  129. }