feat: Access Logging on the user server

Closes: #98

Co-authored-by: Roberto Abdelkader Martínez Pérez <robertomartinezp@gmail.com>
This commit is contained in:
pancho horrillo
2020-12-16 17:51:22 +01:00
parent 41be4f9344
commit 4d05223224
7 changed files with 93 additions and 4 deletions
+31 -1
View File
@@ -21,6 +21,7 @@ import (
"github.com/gorilla/mux"
"github.com/BBVA/kapow/internal/logger"
"github.com/BBVA/kapow/internal/server/model"
)
@@ -30,6 +31,35 @@ func gorillize(rs []model.Route, buildHandler func(model.Route) http.Handler) *m
for _, r := range rs {
m.Handle(r.Pattern, buildHandler(r)).Methods(r.Method)
}
m.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
logger.LogAccess(
r.RemoteAddr,
"-",
"-",
r.Method,
r.RequestURI,
r.Proto,
http.StatusNotFound,
0,
r.Header.Get("Referer"),
r.Header.Get("User-Agent"),
)
})
m.MethodNotAllowedHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusMethodNotAllowed)
logger.LogAccess(
r.RemoteAddr,
"-",
"-",
r.Method,
r.RequestURI,
r.Proto,
http.StatusMethodNotAllowed,
0,
r.Header.Get("Referer"),
r.Header.Get("User-Agent"),
)
})
return m
}
@@ -42,6 +42,8 @@ func handleRouteIDToBody(route model.Route) http.Handler {
func TestGorillizeReturnsAnEmptyMuxWhenAnEmptyRouteList(t *testing.T) {
m := gorillize([]model.Route{}, handlerStatusOK)
m.NotFoundHandler = nil
m.MethodNotAllowedHandler = nil
if !reflect.DeepEqual(*m, *mux.NewRouter()) {
t.Error("Returned mux not empty")
@@ -45,6 +45,7 @@ func handlerBuilder(route model.Route) http.Handler {
Route: route,
Request: r,
Writer: w,
Status: 200,
}
data.Handlers.Add(h)
@@ -78,6 +79,20 @@ func handlerBuilder(route model.Route) http.Handler {
logger.L.Println(err)
}
if r != nil {
logger.LogAccess(
r.RemoteAddr,
h.ID,
"-",
r.Method,
r.RequestURI,
r.Proto,
h.Status,
h.SentBytes,
r.Header.Get("Referer"),
r.Header.Get("User-Agent"),
)
}
})
}
+1 -1
View File
@@ -32,7 +32,7 @@ type SwappableMux struct {
func New() *SwappableMux {
return &SwappableMux{
root: mux.NewRouter(),
root: gorillize([]model.Route{}, handlerBuilder),
}
}