Writing a logger middleware for use with Mux router

A logging middleware is a piece of software that sits between the incoming request and the final handler function in a web application. Its primary purpose is to log information about each request that comes through the application.

There are a few reasons why logging middleware can be useful:

  1. Debugging: Logging middleware can be helpful for debugging issues in your application. If you are seeing strange behavior or errors, the logs generated by the middleware can help you understand what is happening and why.

  2. Monitoring: Logging middleware can also be used to monitor the health and performance of your application. By logging information about each request, you can track things like response times, error rates, and traffic patterns.

  3. Security: In some cases, logging middleware can also be used for security purposes. For example, you might log the IP address of each incoming request to help identify and block malicious activity.

package middleware

import (

const requestIDKey = "REQUEST_ID"

func LoggingMiddleware(logger *log.Logger) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			defer func() {
				requestID, ok := r.Context().Value(requestIDKey).(string)
				if !ok {
					requestID = "unknown"

				logger.Println(requestID, r.Method, r.URL.Path, r.RemoteAddr, r.UserAgent())

			next.ServeHTTP(w, r)

This logging middleware logs some details for every request that comes through the router.

It does this by defining a LoggingMiddleware function that takes in an http.Handler and returns an http.HandlerFunc.

The LoggingMiddleware function itself is an http.HandlerFunc that logs the request URI and then calls the next handler, which can be another middleware in the chain or the final handler.

To use the middleware, you just need to call the Use method on your router and pass in the LoggingMiddleware function.

The middleware will then be applied to every request that comes through the router.

package main

import (

func main() {
	r := mux.NewRouter()