Golang Code

Attach a Logger to your Router

· 90 words · 1 minute read #func #handler #http #log #logger #logging #net #net/http #serve #terminal #time

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.

package main

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

func Logger(inner http.Handler, name string) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		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),
		)
	})
}
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.

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!