logger.go 5.8 KB

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