logger.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. package middleware
  2. import (
  3. "bytes"
  4. "context"
  5. "log"
  6. "net/http"
  7. "os"
  8. "runtime"
  9. "time"
  10. )
  11. var (
  12. // LogEntryCtxKey is the context.Context key to store the request log entry.
  13. LogEntryCtxKey = &contextKey{"LogEntry"}
  14. // DefaultLogger is called by the Logger middleware handler to log each request.
  15. // Its made a package-level variable so that it can be reconfigured for custom
  16. // logging configurations.
  17. DefaultLogger func(next http.Handler) http.Handler
  18. )
  19. // Logger is a middleware that logs the start and end of each request, along
  20. // with some useful data about what was requested, what the response status was,
  21. // and how long it took to return. When standard output is a TTY, Logger will
  22. // print in color, otherwise it will print in black and white. Logger prints a
  23. // request ID if one is provided.
  24. //
  25. // Alternatively, look at https://github.com/goware/httplog for a more in-depth
  26. // http logger with structured logging support.
  27. //
  28. // IMPORTANT NOTE: Logger should go before any other middleware that may change
  29. // the response, such as middleware.Recoverer. Example:
  30. //
  31. // r := chi.NewRouter()
  32. // r.Use(middleware.Logger) // <--<< Logger should come before Recoverer
  33. // r.Use(middleware.Recoverer)
  34. // r.Get("/", handler)
  35. func Logger(next http.Handler) http.Handler {
  36. return DefaultLogger(next)
  37. }
  38. // RequestLogger returns a logger handler using a custom LogFormatter.
  39. func RequestLogger(f LogFormatter) func(next http.Handler) http.Handler {
  40. return func(next http.Handler) http.Handler {
  41. fn := func(w http.ResponseWriter, r *http.Request) {
  42. entry := f.NewLogEntry(r)
  43. ww := NewWrapResponseWriter(w, r.ProtoMajor)
  44. t1 := time.Now()
  45. defer func() {
  46. entry.Write(ww.Status(), ww.BytesWritten(), ww.Header(), time.Since(t1), nil)
  47. }()
  48. next.ServeHTTP(ww, WithLogEntry(r, entry))
  49. }
  50. return http.HandlerFunc(fn)
  51. }
  52. }
  53. // LogFormatter initiates the beginning of a new LogEntry per request.
  54. // See DefaultLogFormatter for an example implementation.
  55. type LogFormatter interface {
  56. NewLogEntry(r *http.Request) LogEntry
  57. }
  58. // LogEntry records the final log when a request completes.
  59. // See defaultLogEntry for an example implementation.
  60. type LogEntry interface {
  61. Write(status, bytes int, header http.Header, elapsed time.Duration, extra interface{})
  62. Panic(v interface{}, stack []byte)
  63. }
  64. // GetLogEntry returns the in-context LogEntry for a request.
  65. func GetLogEntry(r *http.Request) LogEntry {
  66. entry, _ := r.Context().Value(LogEntryCtxKey).(LogEntry)
  67. return entry
  68. }
  69. // WithLogEntry sets the in-context LogEntry for a request.
  70. func WithLogEntry(r *http.Request, entry LogEntry) *http.Request {
  71. r = r.WithContext(context.WithValue(r.Context(), LogEntryCtxKey, entry))
  72. return r
  73. }
  74. // LoggerInterface accepts printing to stdlib logger or compatible logger.
  75. type LoggerInterface interface {
  76. Print(v ...interface{})
  77. }
  78. // DefaultLogFormatter is a simple logger that implements a LogFormatter.
  79. type DefaultLogFormatter struct {
  80. Logger LoggerInterface
  81. NoColor bool
  82. }
  83. // NewLogEntry creates a new LogEntry for the request.
  84. func (l *DefaultLogFormatter) NewLogEntry(r *http.Request) LogEntry {
  85. useColor := !l.NoColor
  86. entry := &defaultLogEntry{
  87. DefaultLogFormatter: l,
  88. request: r,
  89. buf: &bytes.Buffer{},
  90. useColor: useColor,
  91. }
  92. reqID := GetReqID(r.Context())
  93. if reqID != "" {
  94. cW(entry.buf, useColor, nYellow, "[%s] ", reqID)
  95. }
  96. cW(entry.buf, useColor, nCyan, "\"")
  97. cW(entry.buf, useColor, bMagenta, "%s ", r.Method)
  98. scheme := "http"
  99. if r.TLS != nil {
  100. scheme = "https"
  101. }
  102. cW(entry.buf, useColor, nCyan, "%s://%s%s %s\" ", scheme, r.Host, r.RequestURI, r.Proto)
  103. entry.buf.WriteString("from ")
  104. entry.buf.WriteString(r.RemoteAddr)
  105. entry.buf.WriteString(" - ")
  106. return entry
  107. }
  108. type defaultLogEntry struct {
  109. *DefaultLogFormatter
  110. request *http.Request
  111. buf *bytes.Buffer
  112. useColor bool
  113. }
  114. func (l *defaultLogEntry) Write(status, bytes int, header http.Header, elapsed time.Duration, extra interface{}) {
  115. switch {
  116. case status < 200:
  117. cW(l.buf, l.useColor, bBlue, "%03d", status)
  118. case status < 300:
  119. cW(l.buf, l.useColor, bGreen, "%03d", status)
  120. case status < 400:
  121. cW(l.buf, l.useColor, bCyan, "%03d", status)
  122. case status < 500:
  123. cW(l.buf, l.useColor, bYellow, "%03d", status)
  124. default:
  125. cW(l.buf, l.useColor, bRed, "%03d", status)
  126. }
  127. cW(l.buf, l.useColor, bBlue, " %dB", bytes)
  128. l.buf.WriteString(" in ")
  129. if elapsed < 500*time.Millisecond {
  130. cW(l.buf, l.useColor, nGreen, "%s", elapsed)
  131. } else if elapsed < 5*time.Second {
  132. cW(l.buf, l.useColor, nYellow, "%s", elapsed)
  133. } else {
  134. cW(l.buf, l.useColor, nRed, "%s", elapsed)
  135. }
  136. l.Logger.Print(l.buf.String())
  137. }
  138. func (l *defaultLogEntry) Panic(v interface{}, stack []byte) {
  139. PrintPrettyStack(v)
  140. }
  141. func init() {
  142. color := true
  143. if runtime.GOOS == "windows" {
  144. color = false
  145. }
  146. DefaultLogger = RequestLogger(&DefaultLogFormatter{Logger: log.New(os.Stdout, "", log.LstdFlags), NoColor: !color})
  147. }