mirror of
https://github.com/weaveworks/scope.git
synced 2026-02-14 18:09:59 +00:00
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:
@@ -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
|
||||
|
||||
@@ -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{
|
||||
|
||||
Reference in New Issue
Block a user