logger.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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. "net/http"
  9. "os"
  10. "time"
  11. "github.com/mattn/go-isatty"
  12. )
  13. var (
  14. green = string([]byte{27, 91, 57, 55, 59, 52, 50, 109})
  15. white = string([]byte{27, 91, 57, 48, 59, 52, 55, 109})
  16. yellow = string([]byte{27, 91, 57, 48, 59, 52, 51, 109})
  17. red = string([]byte{27, 91, 57, 55, 59, 52, 49, 109})
  18. blue = string([]byte{27, 91, 57, 55, 59, 52, 52, 109})
  19. magenta = string([]byte{27, 91, 57, 55, 59, 52, 53, 109})
  20. cyan = string([]byte{27, 91, 57, 55, 59, 52, 54, 109})
  21. reset = string([]byte{27, 91, 48, 109})
  22. disableColor = false
  23. )
  24. // LoggerConfig defines the config for Logger middleware.
  25. type LoggerConfig struct {
  26. // Optional. Default value is gin.defaultLogFormatter
  27. Formatter LogFormatter
  28. // Output is a writer where logs are written.
  29. // Optional. Default value is gin.DefaultWriter.
  30. Output io.Writer
  31. // SkipPaths is a url path array which logs are not written.
  32. // Optional.
  33. SkipPaths []string
  34. }
  35. // LogFormatter gives the signature of the formatter function passed to LoggerWithFormatter
  36. type LogFormatter func(params LogFormatterParams) string
  37. // LogFormatterParams is the structure any formatter will be handed when time to log comes
  38. type LogFormatterParams struct {
  39. Request *http.Request
  40. TimeStamp time.Time
  41. StatusCode int
  42. Latency time.Duration
  43. ClientIP string
  44. Method string
  45. Path string
  46. ErrorMessage string
  47. IsTerm bool
  48. }
  49. // defaultLogFormatter is the default log format function Logger middleware uses.
  50. var defaultLogFormatter = func(param LogFormatterParams) string {
  51. var statusColor, methodColor, resetColor string
  52. if param.IsTerm {
  53. statusColor = colorForStatus(param.StatusCode)
  54. methodColor = colorForMethod(param.Method)
  55. resetColor = reset
  56. }
  57. return fmt.Sprintf("[GIN] %v |%s %3d %s| %13v | %15s |%s %-7s %s %s\n%s",
  58. param.TimeStamp.Format("2006/01/02 - 15:04:05"),
  59. statusColor, param.StatusCode, resetColor,
  60. param.Latency,
  61. param.ClientIP,
  62. methodColor, param.Method, resetColor,
  63. param.Path,
  64. param.ErrorMessage,
  65. )
  66. }
  67. // DisableConsoleColor disables color output in the console.
  68. func DisableConsoleColor() {
  69. disableColor = true
  70. }
  71. // ErrorLogger returns a handlerfunc for any error type.
  72. func ErrorLogger() HandlerFunc {
  73. return ErrorLoggerT(ErrorTypeAny)
  74. }
  75. // ErrorLoggerT returns a handlerfunc for a given error type.
  76. func ErrorLoggerT(typ ErrorType) HandlerFunc {
  77. return func(c *Context) {
  78. c.Next()
  79. errors := c.Errors.ByType(typ)
  80. if len(errors) > 0 {
  81. c.JSON(-1, errors)
  82. }
  83. }
  84. }
  85. // Logger instances a Logger middleware that will write the logs to gin.DefaultWriter.
  86. // By default gin.DefaultWriter = os.Stdout.
  87. func Logger() HandlerFunc {
  88. return LoggerWithConfig(LoggerConfig{})
  89. }
  90. // LoggerWithFormatter instance a Logger middleware with the specified log format function.
  91. func LoggerWithFormatter(f LogFormatter) HandlerFunc {
  92. return LoggerWithConfig(LoggerConfig{
  93. Formatter: f,
  94. })
  95. }
  96. // LoggerWithWriter instance a Logger middleware with the specified writer buffer.
  97. // Example: os.Stdout, a file opened in write mode, a socket...
  98. func LoggerWithWriter(out io.Writer, notlogged ...string) HandlerFunc {
  99. return LoggerWithConfig(LoggerConfig{
  100. Output: out,
  101. SkipPaths: notlogged,
  102. })
  103. }
  104. // LoggerWithConfig instance a Logger middleware with config.
  105. func LoggerWithConfig(conf LoggerConfig) HandlerFunc {
  106. formatter := conf.Formatter
  107. if formatter == nil {
  108. formatter = defaultLogFormatter
  109. }
  110. out := conf.Output
  111. if out == nil {
  112. out = DefaultWriter
  113. }
  114. notlogged := conf.SkipPaths
  115. isTerm := true
  116. if w, ok := out.(*os.File); !ok ||
  117. (os.Getenv("TERM") == "dumb" || (!isatty.IsTerminal(w.Fd()) && !isatty.IsCygwinTerminal(w.Fd()))) ||
  118. disableColor {
  119. isTerm = false
  120. }
  121. var skip map[string]struct{}
  122. if length := len(notlogged); length > 0 {
  123. skip = make(map[string]struct{}, length)
  124. for _, path := range notlogged {
  125. skip[path] = struct{}{}
  126. }
  127. }
  128. return func(c *Context) {
  129. // Start timer
  130. start := time.Now()
  131. path := c.Request.URL.Path
  132. raw := c.Request.URL.RawQuery
  133. // Process request
  134. c.Next()
  135. // Log only when path is not being skipped
  136. if _, ok := skip[path]; !ok {
  137. param := LogFormatterParams{
  138. Request: c.Request,
  139. IsTerm: isTerm,
  140. }
  141. // Stop timer
  142. param.TimeStamp = time.Now()
  143. param.Latency = param.TimeStamp.Sub(start)
  144. param.ClientIP = c.ClientIP()
  145. param.Method = c.Request.Method
  146. param.StatusCode = c.Writer.Status()
  147. param.ErrorMessage = c.Errors.ByType(ErrorTypePrivate).String()
  148. if raw != "" {
  149. path = path + "?" + raw
  150. }
  151. param.Path = path
  152. fmt.Fprintf(out, formatter(param))
  153. }
  154. }
  155. }
  156. func colorForStatus(code int) string {
  157. switch {
  158. case code >= http.StatusOK && code < http.StatusMultipleChoices:
  159. return green
  160. case code >= http.StatusMultipleChoices && code < http.StatusBadRequest:
  161. return white
  162. case code >= http.StatusBadRequest && code < http.StatusInternalServerError:
  163. return yellow
  164. default:
  165. return red
  166. }
  167. }
  168. func colorForMethod(method string) string {
  169. switch method {
  170. case "GET":
  171. return blue
  172. case "POST":
  173. return cyan
  174. case "PUT":
  175. return yellow
  176. case "DELETE":
  177. return red
  178. case "PATCH":
  179. return green
  180. case "HEAD":
  181. return magenta
  182. case "OPTIONS":
  183. return white
  184. default:
  185. return reset
  186. }
  187. }