logger.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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 an 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 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]any
  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. param.Latency = param.Latency.Truncate(time.Second)
  121. }
  122. return fmt.Sprintf("[GIN] %v |%s %3d %s| %13v | %15s |%s %-7s %s %#v\n%s",
  123. param.TimeStamp.Format("2006/01/02 - 15:04:05"),
  124. statusColor, param.StatusCode, resetColor,
  125. param.Latency,
  126. param.ClientIP,
  127. methodColor, param.Method, resetColor,
  128. param.Path,
  129. param.ErrorMessage,
  130. )
  131. }
  132. // DisableConsoleColor disables color output in the console.
  133. func DisableConsoleColor() {
  134. consoleColorMode = disableColor
  135. }
  136. // ForceConsoleColor force color output in the console.
  137. func ForceConsoleColor() {
  138. consoleColorMode = forceColor
  139. }
  140. // ErrorLogger returns a HandlerFunc for any error type.
  141. func ErrorLogger() HandlerFunc {
  142. return ErrorLoggerT(ErrorTypeAny)
  143. }
  144. // ErrorLoggerT returns a HandlerFunc for a given error type.
  145. func ErrorLoggerT(typ ErrorType) HandlerFunc {
  146. return func(c *Context) {
  147. c.Next()
  148. errors := c.Errors.ByType(typ)
  149. if len(errors) > 0 {
  150. c.JSON(-1, errors)
  151. }
  152. }
  153. }
  154. // Logger instances a Logger middleware that will write the logs to gin.DefaultWriter.
  155. // By default, gin.DefaultWriter = os.Stdout.
  156. func Logger() HandlerFunc {
  157. return LoggerWithConfig(LoggerConfig{})
  158. }
  159. // LoggerWithFormatter instance a Logger middleware with the specified log format function.
  160. func LoggerWithFormatter(f LogFormatter) HandlerFunc {
  161. return LoggerWithConfig(LoggerConfig{
  162. Formatter: f,
  163. })
  164. }
  165. // LoggerWithWriter instance a Logger middleware with the specified writer buffer.
  166. // Example: os.Stdout, a file opened in write mode, a socket...
  167. func LoggerWithWriter(out io.Writer, notlogged ...string) HandlerFunc {
  168. return LoggerWithConfig(LoggerConfig{
  169. Output: out,
  170. SkipPaths: notlogged,
  171. })
  172. }
  173. // LoggerWithConfig instance a Logger middleware with config.
  174. func LoggerWithConfig(conf LoggerConfig) HandlerFunc {
  175. formatter := conf.Formatter
  176. if formatter == nil {
  177. formatter = defaultLogFormatter
  178. }
  179. out := conf.Output
  180. if out == nil {
  181. out = DefaultWriter
  182. }
  183. notlogged := conf.SkipPaths
  184. isTerm := true
  185. if w, ok := out.(*os.File); !ok || os.Getenv("TERM") == "dumb" ||
  186. (!isatty.IsTerminal(w.Fd()) && !isatty.IsCygwinTerminal(w.Fd())) {
  187. isTerm = false
  188. }
  189. var skip map[string]struct{}
  190. if length := len(notlogged); length > 0 {
  191. skip = make(map[string]struct{}, length)
  192. for _, path := range notlogged {
  193. skip[path] = struct{}{}
  194. }
  195. }
  196. return func(c *Context) {
  197. // Start timer
  198. start := time.Now()
  199. path := c.Request.URL.Path
  200. raw := c.Request.URL.RawQuery
  201. // Process request
  202. c.Next()
  203. // Log only when path is not being skipped
  204. if _, ok := skip[path]; !ok {
  205. param := LogFormatterParams{
  206. Request: c.Request,
  207. isTerm: isTerm,
  208. Keys: c.Keys,
  209. }
  210. // Stop timer
  211. param.TimeStamp = time.Now()
  212. param.Latency = param.TimeStamp.Sub(start)
  213. param.ClientIP = c.ClientIP()
  214. param.Method = c.Request.Method
  215. param.StatusCode = c.Writer.Status()
  216. param.ErrorMessage = c.Errors.ByType(ErrorTypePrivate).String()
  217. param.BodySize = c.Writer.Size()
  218. if raw != "" {
  219. path = path + "?" + raw
  220. }
  221. param.Path = path
  222. fmt.Fprint(out, formatter(param))
  223. }
  224. }
  225. }