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
This commit is contained in:
Tom Wilkie
2016-10-07 18:03:36 -07:00
committed by GitHub
parent 33ec1acf67
commit 727404c9b8
2 changed files with 24 additions and 5 deletions

View File

@@ -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

View File

@@ -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{