handler.go 3.3 KB

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