From feb3471e7afc30f68bf49129d71ee190581f223b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marko=20Tikvi=C4=87?= Date: Mon, 22 Oct 2018 09:33:33 +0200 Subject: [PATCH] refactored logging middleware --- middleware.go | 28 ---------------------------- middleware_log.go | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 28 deletions(-) create mode 100644 middleware_log.go diff --git a/middleware.go b/middleware.go index f4f09d6..4955a60 100644 --- a/middleware.go +++ b/middleware.go @@ -2,9 +2,6 @@ package webutility import ( "net/http" - "time" - - "git.to-net.rs/marko.tikvic/gologger" ) func SetHeaders(h http.HandlerFunc) http.HandlerFunc { @@ -39,31 +36,6 @@ func ParseMultipartForm(h http.HandlerFunc) http.HandlerFunc { } } -var trafficLogger *gologger.Logger - -func EnableLogging(log string) error { - var err error - trafficLogger, err = gologger.New(log, gologger.MaxLogSize5MB) - return err -} - -func Log(h http.HandlerFunc) http.HandlerFunc { - return func(w http.ResponseWriter, req *http.Request) { - t1 := time.Now() - - in := trafficLogger.RequestLog(req, "") - - wRec := WrapWithStatusRecorder(w) - h(wRec, req) - - t2 := time.Now() - - out := trafficLogger.ResponseLog(wRec.Status(), t2.Sub(t1), 0) - - trafficLogger.LogHTTPTraffic(in, out) - } -} - func Auth(roles string, h http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { if _, err := AuthCheck(req, roles); err != nil { diff --git a/middleware_log.go b/middleware_log.go new file mode 100644 index 0000000..c1ffe16 --- /dev/null +++ b/middleware_log.go @@ -0,0 +1,34 @@ +package webutility + +import ( + "net/http" + "time" + + "git.to-net.rs/marko.tikvic/gologger" +) + +var trafficLogger *gologger.Logger + +func EnableLogging(log string) (err error) { + trafficLogger, err = gologger.New(log, gologger.MaxLogSize5MB) + return err +} + +func Log(h http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, req *http.Request) { + t1 := time.Now() + + claims, _ := GetTokenClaims(req) + + in := trafficLogger.RequestLog(req, claims.Username) + + wRec := WrapWithStatusRecorder(w) + h(wRec, req) + + t2 := time.Now() + + out := trafficLogger.ResponseLog(wRec.Status(), t2.Sub(t1), 0) + + trafficLogger.LogHTTPTraffic(in, out) + } +} -- 1.8.1.2