logger.go 6.5 KB

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