Commit feb3471e7afc30f68bf49129d71ee190581f223b

Authored by Marko Tikvić
1 parent 368c7f87bf
Exists in master

refactored logging middleware

Showing 2 changed files with 34 additions and 28 deletions   Show diff stats
... ... @@ -2,9 +2,6 @@ package webutility
2 2  
3 3 import (
4 4 "net/http"
5   - "time"
6   -
7   - "git.to-net.rs/marko.tikvic/gologger"
8 5 )
9 6  
10 7 func SetHeaders(h http.HandlerFunc) http.HandlerFunc {
... ... @@ -39,31 +36,6 @@ func ParseMultipartForm(h http.HandlerFunc) http.HandlerFunc {
39 36 }
40 37 }
41 38  
42   -var trafficLogger *gologger.Logger
43   -
44   -func EnableLogging(log string) error {
45   - var err error
46   - trafficLogger, err = gologger.New(log, gologger.MaxLogSize5MB)
47   - return err
48   -}
49   -
50   -func Log(h http.HandlerFunc) http.HandlerFunc {
51   - return func(w http.ResponseWriter, req *http.Request) {
52   - t1 := time.Now()
53   -
54   - in := trafficLogger.RequestLog(req, "")
55   -
56   - wRec := WrapWithStatusRecorder(w)
57   - h(wRec, req)
58   -
59   - t2 := time.Now()
60   -
61   - out := trafficLogger.ResponseLog(wRec.Status(), t2.Sub(t1), 0)
62   -
63   - trafficLogger.LogHTTPTraffic(in, out)
64   - }
65   -}
66   -
67 39 func Auth(roles string, h http.HandlerFunc) http.HandlerFunc {
68 40 return func(w http.ResponseWriter, req *http.Request) {
69 41 if _, err := AuthCheck(req, roles); err != nil {
... ...
middleware_log.go
... ... @@ -0,0 +1,34 @@
  1 +package webutility
  2 +
  3 +import (
  4 + "net/http"
  5 + "time"
  6 +
  7 + "git.to-net.rs/marko.tikvic/gologger"
  8 +)
  9 +
  10 +var trafficLogger *gologger.Logger
  11 +
  12 +func EnableLogging(log string) (err error) {
  13 + trafficLogger, err = gologger.New(log, gologger.MaxLogSize5MB)
  14 + return err
  15 +}
  16 +
  17 +func Log(h http.HandlerFunc) http.HandlerFunc {
  18 + return func(w http.ResponseWriter, req *http.Request) {
  19 + t1 := time.Now()
  20 +
  21 + claims, _ := GetTokenClaims(req)
  22 +
  23 + in := trafficLogger.RequestLog(req, claims.Username)
  24 +
  25 + wRec := WrapWithStatusRecorder(w)
  26 + h(wRec, req)
  27 +
  28 + t2 := time.Now()
  29 +
  30 + out := trafficLogger.ResponseLog(wRec.Status(), t2.Sub(t1), 0)
  31 +
  32 + trafficLogger.LogHTTPTraffic(in, out)
  33 + }
  34 +}
... ...