From 727404c9b84dd24f1f94e578613ce091d1a5bfd6 Mon Sep 17 00:00:00 2001 From: Tom Wilkie Date: Fri, 7 Oct 2016 18:03:36 -0700 Subject: [PATCH] Extend logging middleware to optionally only log failed HTTP requests (#1909) * Extend logging middleware to optionally only log failed HTTP requests * Add a preconfigured logger for logging failed requests, use it in the app. * Wide definition of success --- common/middleware/logging.go | 27 +++++++++++++++++++++++---- prog/app.go | 2 +- 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/common/middleware/logging.go b/common/middleware/logging.go index 8bdcc622c..7bda6377f 100644 --- a/common/middleware/logging.go +++ b/common/middleware/logging.go @@ -10,16 +10,35 @@ import ( log "github.com/Sirupsen/logrus" ) -// Logging middleware logs each HTTP request method, path, response code and duration. -var Logging = Func(func(next http.Handler) http.Handler { +// Log middleware logs http requests +type Log struct { + LogSuccess bool // LogSuccess true -> log successful queries; false -> only log failed queries +} + +// Wrap implements Middleware +func (l Log) Wrap(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { begin := time.Now() uri := r.RequestURI // capture the URI before running next, as it may get rewritten i := &interceptor{ResponseWriter: w, statusCode: http.StatusOK} next.ServeHTTP(i, r) - log.Infof("%s %s (%d) %s", r.Method, uri, i.statusCode, time.Since(begin)) + if l.LogSuccess || !(100 <= i.statusCode && i.statusCode < 400) { + log.Infof("%s %s (%d) %s", r.Method, uri, i.statusCode, time.Since(begin)) + } }) -}) +} + +// Logging middleware logs each HTTP request method, path, response code and +// duration for all HTTP requests. +var Logging = Log{ + LogSuccess: true, +} + +// LogFailed middleware logs each HTTP request method, path, response code and +// duration for non-2xx HTTP requests. +var LogFailed = Log{ + LogSuccess: false, +} // interceptor implements WriteHeader to intercept status codes. WriteHeader // may not be called on success, so initialize statusCode with the status you diff --git a/prog/app.go b/prog/app.go index dfba8e16a..a830c3525 100644 --- a/prog/app.go +++ b/prog/app.go @@ -269,7 +269,7 @@ func appMain(flags appFlags) { handler := router(collector, controlRouter, pipeRouter, flags.externalUI) if flags.logHTTP { - handler = middleware.Logging.Wrap(handler) + handler = middleware.LogFailed.Wrap(handler) } server := &graceful.Server{