logger.go 5.9 KB

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