logger.go 6.4 KB

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