Skip to content

Commit

Permalink
Add logger for action handlers
Browse files Browse the repository at this point in the history
  • Loading branch information
pawiecz committed Dec 31, 2017
1 parent 7e779a3 commit b5b1c97
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
19 changes: 19 additions & 0 deletions logger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package main

import (
"log"
"net/http"
"time"

"github.com/julienschmidt/httprouter"
)

// Logger wraps the handler function with basic log message.
func Logger(fn func(w http.ResponseWriter, r *http.Request, param httprouter.Params)) func(w http.ResponseWriter, r *http.Request, param httprouter.Params) {
return func(w http.ResponseWriter, r *http.Request, param httprouter.Params) {
log.Printf("[%s %s] Requested", r.Method, r.URL.Path)
start := time.Now()
fn(w, r, param)
log.Printf("[%s %s] Completed in %v", r.Method, r.URL.Path, time.Since(start))
}
}
2 changes: 1 addition & 1 deletion routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ func AllRoutes() Routes {
func NewRouter(routes Routes) *httprouter.Router {
router := httprouter.New()
for _, route := range routes {
router.Handle(route.Method, route.Path, route.HandlerFunc)
router.Handle(route.Method, route.Path, Logger(route.HandlerFunc))
}
return router
}

0 comments on commit b5b1c97

Please sign in to comment.