title: Go : add logging to each router
body: <p>Go : add logging to each router</p>
  
  <p>I want to log all my network request in Go web app.</p>
  
  <p>Something like negroni:</p>
  
  <pre><code>// https://github.com/codegangsta/negroni/blob/master/logger.go
  // NewLogger returns a new Logger instance
  func NewLogger() *Logger {
    return &amp;Logger{log.New(os.Stdout, "[negroni] ", 0)}
  }
  
  func (l *Logger) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
    start := time.Now()
    l.Printf("Started %s %s", r.Method, r.URL.Path)
  
    next(rw, r)
  
    res := rw.(ResponseWriter)
    l.Printf("Completed %v %s in %v", res.Status(), http.StatusText(res.Status()), time.Since(start))
  }
  </code></pre>
  
  <p>So here's my code:</p>
  
  <pre><code>router := httprouter.New()
  
  handler := func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
    type Page struct {
      Title string
    }
    tp := template.Must(template.ParseFiles("templates/main.html", "templates/base.html"))
    err := tp.ExecuteTemplate(w, "base", &amp;Page{Title: "AAA"})
    if err != nil {
      log.Fatal(err)
  }
  
  router.Handle("GET", "/", handler)
  
  l := log.New(os.Stdout, "[AAA] ", 0)
  l.Printf("Listening 0.0.0.0%s", PORT)
  
  l.Fatal(http.ListenAndServe(PORT, router))
  </code></pre>
  
  <p>If I want to do this, I have to add <code>start := time.Now()</code> and <code>time.Since(start)</code> manually to each router in my code.package main</p>
  
  <p>I think I should wrap it and use interface but don't know how to get started.</p>
  
  <p>How do I implement one simple logging interface and apply all the routed handlers so that I can debug with all the loggings...</p>
  
  <p>Negroni does like:</p>
  
  <pre><code>router := mux.NewRouter()
  router.HandleFunc("/", HomeHandler)
  
  n := negroni.New(Middleware1, Middleware2)
  // Or use a middleware with the Use() function
  n.Use(Middleware3)
  // router goes last
  n.UseHandler(router)
  
  n.Run(":3000")
  </code></pre>