logger.go 6.0 KB

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