handler.go 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package logging
  2. import (
  3. "net"
  4. "net/http"
  5. "time"
  6. "github.com/sirupsen/logrus"
  7. )
  8. // LoggerHandler creates a logger handler
  9. type LoggerHandler struct {
  10. name string
  11. logger *logrus.Logger
  12. next http.Handler
  13. }
  14. // NewLoggerHandler returns the given http.Handler with the logger integrated.
  15. func NewLoggerHandler(name string, logger *Logger, next http.Handler) http.Handler {
  16. h := RequestID(logger.GetTraceHeader())
  17. return h(&LoggerHandler{
  18. name: name,
  19. logger: logger.GetImpl(),
  20. next: next,
  21. })
  22. }
  23. // ServeHTTP implements the http.Handler and call to the handler to log with a
  24. // custom http.ResponseWriter that records the response code and the number of
  25. // bytes sent.
  26. func (l *LoggerHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  27. t := time.Now()
  28. rw := NewResponseLogger(w)
  29. l.next.ServeHTTP(rw, r)
  30. d := time.Now().Sub(t)
  31. l.writeEntry(rw, r, t, d)
  32. }
  33. // writeEntry writes to the Logger writer the request information in the logger.
  34. func (l *LoggerHandler) writeEntry(w ResponseLogger, r *http.Request, t time.Time, d time.Duration) {
  35. var reqID, user string
  36. ctx := r.Context()
  37. if v, ok := ctx.Value(RequestIDKey).(string); ok && v != "" {
  38. reqID = v
  39. }
  40. if v, ok := ctx.Value(UserIDKey).(string); ok && v != "" {
  41. user = v
  42. }
  43. // Remote hostname
  44. addr, _, err := net.SplitHostPort(r.RemoteAddr)
  45. if err != nil {
  46. addr = r.RemoteAddr
  47. }
  48. // From https://github.com/gorilla/handlers
  49. uri := r.RequestURI
  50. // Requests using the CONNECT method over HTTP/2.0 must use
  51. // the authority field (aka r.Host) to identify the target.
  52. // Refer: https://httpwg.github.io/specs/rfc7540.html#CONNECT
  53. if r.ProtoMajor == 2 && r.Method == "CONNECT" {
  54. uri = r.Host
  55. }
  56. if uri == "" {
  57. uri = r.URL.RequestURI()
  58. }
  59. status := w.StatusCode()
  60. fields := logrus.Fields{
  61. "request-id": reqID,
  62. "remote-address": addr,
  63. "name": l.name,
  64. "user-id": user,
  65. "time": t.Format(time.RFC3339),
  66. "duration-ns": d.Nanoseconds(),
  67. "duration": d.String(),
  68. "method": r.Method,
  69. "path": uri,
  70. "protocol": r.Proto,
  71. "status": status,
  72. "size": w.Size(),
  73. "referer": r.Referer(),
  74. "user-agent": r.UserAgent(),
  75. }
  76. for k, v := range w.Fields() {
  77. fields[k] = v
  78. }
  79. switch {
  80. case status < http.StatusBadRequest:
  81. l.logger.WithFields(fields).Info()
  82. case status < http.StatusInternalServerError:
  83. l.logger.WithFields(fields).Warn()
  84. default:
  85. l.logger.WithFields(fields).Error()
  86. }
  87. }