4
0

handler.go 3.1 KB

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