Attach a Logger to your Router

· 209 words · 1 minute read

If you’re working with the net/http package, you can easily create a router to pass different http calls to different functions. A logger allows you to keep track of these calls. In this example, we just log the call to the terminal (or stdout). To use this logger wrap any handlers you have with Logger().

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package main

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

func main() {

    // Specify our ExampleHandler and wrap the Logger around it.
    http.Handle("/", Logger(http.HandlerFunc(ExampleHandler), "WEB"))

    log.Println("** Service Started on Port 8080 **")
    if err := http.ListenAndServe(":8080", nil); err != nil {
        panic(err)
    }
}

// Logger records incoming requests and uses the log package to print http method,
// route url and duration to screen/logs.
func Logger(inner http.Handler, name string) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

        // Save start time to calculate duration
        start := time.Now()

        inner.ServeHTTP(w, r)

        log.Printf(
            "%s\t\t%s\t\t%s\t\t%s",
            r.Method,
            r.RequestURI,
            name,
            time.Since(start),
        )
    })
}

func ExampleHandler(w http.ResponseWriter, r *http.Request) {
    w.Header().Add("Content-Type", "application/json")
    io.WriteString(w, `{"status":"ok"}`)
}

Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!