logger.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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. type consoleColorModeValue int
  14. const (
  15. autoColor consoleColorModeValue = iota
  16. disableColor
  17. forceColor
  18. )
  19. const (
  20. green = "\033[97;42m"
  21. white = "\033[90;47m"
  22. yellow = "\033[90;43m"
  23. red = "\033[97;41m"
  24. blue = "\033[97;44m"
  25. magenta = "\033[97;45m"
  26. cyan = "\033[97;46m"
  27. reset = "\033[0m"
  28. )
  29. var consoleColorMode = autoColor
  30. // LoggerConfig defines the config for Logger middleware.
  31. type LoggerConfig struct {
  32. // Optional. Default value is gin.defaultLogFormatter
  33. Formatter LogFormatter
  34. // Output is a writer where logs are written.
  35. // Optional. Default value is gin.DefaultWriter.
  36. Output io.Writer
  37. // SkipPaths is a url path array which logs are not written.
  38. // Optional.
  39. SkipPaths []string
  40. }
  41. // LogFormatter gives the signature of the formatter function passed to LoggerWithFormatter
  42. type LogFormatter func(params LogFormatterParams) string
  43. // LogFormatterParams is the structure any formatter will be handed when time to log comes
  44. type LogFormatterParams struct {
  45. Request *http.Request
  46. // TimeStamp shows the time after the server returns a response.
  47. TimeStamp time.Time
  48. // StatusCode is HTTP response code.
  49. StatusCode int
  50. // Latency is how much time the server cost to process a certain request.
  51. Latency time.Duration
  52. // ClientIP equals Context's ClientIP method.
  53. ClientIP string
  54. // Method is the HTTP method given to the request.
  55. Method string
  56. // Path is a path the client requests.
  57. Path string
  58. // ErrorMessage is set if error has occurred in processing the request.
  59. ErrorMessage string
  60. // isTerm shows whether does gin's output descriptor refers to a terminal.
  61. isTerm bool
  62. // BodySize is the size of the Response Body
  63. BodySize int
  64. // Keys are the keys set on the request's context.
  65. Keys map[string]interface{}
  66. }
  67. // StatusCodeColor is the ANSI color for appropriately logging http status code to a terminal.
  68. func (p *LogFormatterParams) StatusCodeColor() string {
  69. code := p.StatusCode
  70. switch {
  71. case code >= http.StatusOK && code < http.StatusMultipleChoices:
  72. return green
  73. case code >= http.StatusMultipleChoices && code < http.StatusBadRequest:
  74. return white
  75. case code >= http.StatusBadRequest && code < http.StatusInternalServerError:
  76. return yellow
  77. default:
  78. return red
  79. }
  80. }
  81. // MethodColor is the ANSI color for appropriately logging http method to a terminal.
  82. func (p *LogFormatterParams) MethodColor() string {
  83. method := p.Method
  84. switch method {
  85. case http.MethodGet:
  86. return blue
  87. case http.MethodPost:
  88. return cyan
  89. case http.MethodPut:
  90. return yellow
  91. case http.MethodDelete:
  92. return red
  93. case http.MethodPatch:
  94. return green
  95. case http.MethodHead:
  96. return magenta
  97. case http.MethodOptions:
  98. return white
  99. default:
  100. return reset
  101. }
  102. }
  103. // ResetColor resets all escape attributes.
  104. func (p *LogFormatterParams) ResetColor() string {
  105. return reset
  106. }
  107. // IsOutputColor indicates whether can colors be outputted to the log.
  108. func (p *LogFormatterParams) IsOutputColor() bool {
  109. return consoleColorMode == forceColor || (consoleColorMode == autoColor && p.isTerm)
  110. }
  111. // defaultLogFormatter is the default log format function Logger middleware uses.
  112. var defaultLogFormatter = func(param LogFormatterParams) string {
  113. var statusColor, methodColor, resetColor string
  114. if param.IsOutputColor() {
  115. statusColor = param.StatusCodeColor()
  116. methodColor = param.MethodColor()
  117. resetColor = param.ResetColor()
  118. }
  119. if param.Latency > time.Minute {
  120. // Truncate in a golang < 1.8 safe way
  121. param.Latency = param.Latency - param.Latency%time.Second
  122. }
  123. return fmt.Sprintf("[GIN] %v |%s %3d %s| %13v | %15s |%s %-7s %s %#v\n%s",
  124. param.TimeStamp.Format("2006/01/02 - 15:04:05"),
  125. statusColor, param.StatusCode, resetColor,
  126. param.Latency,
  127. param.ClientIP,
  128. methodColor, param.Method, resetColor,
  129. param.Path,
  130. param.ErrorMessage,
  131. )
  132. }
  133. // DisableConsoleColor disables color output in the console.
  134. func DisableConsoleColor() {
  135. consoleColorMode = disableColor
  136. }
  137. // ForceConsoleColor force color output in the console.
  138. func ForceConsoleColor() {
  139. consoleColorMode = forceColor
  140. }
  141. // ErrorLogger returns a handlerfunc for any error type.
  142. func ErrorLogger() HandlerFunc {
  143. return ErrorLoggerT(ErrorTypeAny)
  144. }
  145. // ErrorLoggerT returns a handlerfunc for a given error type.
  146. func ErrorLoggerT(typ ErrorType) HandlerFunc {
  147. return func(c *Context) {
  148. c.Next()
  149. errors := c.Errors.ByType(typ)
  150. if len(errors) > 0 {
  151. c.JSON(-1, errors)
  152. }
  153. }
  154. }
  155. // Logger instances a Logger middleware that will write the logs to gin.DefaultWriter.
  156. // By default gin.DefaultWriter = os.Stdout.
  157. func Logger() HandlerFunc {
  158. return LoggerWithConfig(LoggerConfig{})
  159. }
  160. // LoggerWithFormatter instance a Logger middleware with the specified log format function.
  161. func LoggerWithFormatter(f LogFormatter) HandlerFunc {
  162. return LoggerWithConfig(LoggerConfig{
  163. Formatter: f,
  164. })
  165. }
  166. // LoggerWithWriter instance a Logger middleware with the specified writer buffer.
  167. // Example: os.Stdout, a file opened in write mode, a socket...
  168. func LoggerWithWriter(out io.Writer, notlogged ...string) HandlerFunc {
  169. return LoggerWithConfig(LoggerConfig{
  170. Output: out,
  171. SkipPaths: notlogged,
  172. })
  173. }
  174. // LoggerWithConfig instance a Logger middleware with config.
  175. func LoggerWithConfig(conf LoggerConfig) HandlerFunc {
  176. formatter := conf.Formatter
  177. if formatter == nil {
  178. formatter = defaultLogFormatter
  179. }
  180. out := conf.Output
  181. if out == nil {
  182. out = DefaultWriter
  183. }
  184. notlogged := conf.SkipPaths
  185. isTerm := true
  186. if w, ok := out.(*os.File); !ok || os.Getenv("TERM") == "dumb" ||
  187. (!isatty.IsTerminal(w.Fd()) && !isatty.IsCygwinTerminal(w.Fd())) {
  188. isTerm = false
  189. }
  190. var skip map[string]struct{}
  191. if length := len(notlogged); length > 0 {
  192. skip = make(map[string]struct{}, length)
  193. for _, path := range notlogged {
  194. skip[path] = struct{}{}
  195. }
  196. }
  197. return func(c *Context) {
  198. // Start timer
  199. start := time.Now()
  200. path := c.Request.URL.Path
  201. raw := c.Request.URL.RawQuery
  202. // Process request
  203. c.Next()
  204. // Log only when path is not being skipped
  205. if _, ok := skip[path]; !ok {
  206. param := LogFormatterParams{
  207. Request: c.Request,
  208. isTerm: isTerm,
  209. Keys: c.Keys,
  210. }
  211. // Stop timer
  212. param.TimeStamp = time.Now()
  213. param.Latency = param.TimeStamp.Sub(start)
  214. param.ClientIP = c.ClientIP()
  215. param.Method = c.Request.Method
  216. param.StatusCode = c.Writer.Status()
  217. param.ErrorMessage = c.Errors.ByType(ErrorTypePrivate).String()
  218. param.BodySize = c.Writer.Size()
  219. if raw != "" {
  220. path = path + "?" + raw
  221. }
  222. param.Path = path
  223. fmt.Fprint(out, formatter(param))
  224. }
  225. }
  226. }