Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 39 ยท Middleware

Logger and Recovery Middleware in Gin

Learn what gin.Logger and gin.Recovery do, customize the log format and output, skip noisy paths, handle panics with a JSON 500, and build runnable logger and recovery stand-ins with net/http.

Every gin.Default() engine ships with two middleware already attached: Logger writes one line per request, and Recovery catches panics so that one bad request does not take down your server. They are the most-used middleware in the Gin world, and knowing how they behave (and how to replace them) is basic production hygiene. This lesson follows Middleware Basics and prepares you for writing your own middleware.

Gin does not run on this site. The Gin code is read-only; each section has a runnable stand-in built on net/http that does the same job, so you can watch a logger and a recovery handler work.

What gin.Default() gives you

Go
r := gin.Default()
// is the same as:
r := gin.New()
r.Use(gin.Logger(), gin.Recovery())

With gin.New() you start with nothing and pick what you need. Many production services use gin.New() and add their own structured logger.

The Logger

In debug mode each request prints a line like this:

TEXT
[GIN] 2026/03/04 - 10:15:30 | 200 |     1.204ms |       127.0.0.1 | GET      "/books?page=2"

The fields are the timestamp, status code, latency, client IP, method and path. The logger writes after the handler finishes (it calls c.Next() first), which is how it knows the status and the duration.

Changing the output

Go
f, _ := os.Create("access.log")
gin.DefaultWriter = io.MultiWriter(f, os.Stdout) // set BEFORE gin.Default()
r := gin.Default()

gin.DefaultWriter controls where the logger writes, and gin.DefaultErrorWriter is used for Recovery and for debug warnings.

Changing the format

gin.LoggerWithFormatter lets you build any line you want, for example JSON for a log pipeline:

Go
r.Use(gin.LoggerWithFormatter(func(p gin.LogFormatterParams) string {
	b, _ := json.Marshal(map[string]any{
		"time":    p.TimeStamp.Format(time.RFC3339),
		"status":  p.StatusCode,
		"method":  p.Method,
		"path":    p.Path,
		"ip":      p.ClientIP,
		"latency": p.Latency.String(),
		"error":   p.ErrorMessage,
	})
	return string(b) + "\n"
}))

Skipping noisy paths

Health checks fire every few seconds and fill the log. Use LoggerWithConfig:

Go
r.Use(gin.LoggerWithConfig(gin.LoggerConfig{
	SkipPaths: []string{"/healthz", "/metrics"},
}))

Be careful what you log. Query strings can carry tokens (?api_key=...) and reset codes. Log the path without the query for sensitive routes, never log request bodies that may contain passwords, and never log Authorization headers.

Recovery

In Go, a panic that is not recovered terminates the goroutine, and in a plain program would crash it. The net/http server catches panics per request (it logs a stack trace and drops the connection), but the client gets no useful response. Gin's Recovery middleware does better: it recovers, writes the stack trace to the error log and answers 500 Internal Server Error.

Go
r.Use(gin.Recovery())
// or choose your own response:
r.Use(gin.CustomRecovery(func(c *gin.Context, recovered any) {
	log.Printf("panic: %v", recovered)
	c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{
		"error": gin.H{"code": "internal", "message": "something went wrong"},
	})
}))

Recovery protects against nil pointer dereferences, index out of range and explicit panic(...) calls, but not against panics in goroutines you start yourself. Those run outside the middleware chain, so wrap them with their own defer recover().

Panics are for programmer errors. Do not use them for ordinary failures such as "user not found"; return an error and answer with a proper status, as in HTTP Status Codes and Error Responses.

Order matters

Put Recovery outside (before) any middleware that might panic, and Logger near the outside so it records the final status, including the 500 Recovery produces:

Go
r := gin.New()
r.Use(gin.Recovery())   // outermost: catches panics from everything below
r.Use(requestID())      // custom middleware
r.Use(gin.Logger())     // logs the result

The default order (Logger, then Recovery) already makes the Logger report 500 for a recovered panic, because Recovery sits inside it and writes the status before control returns to the Logger.

Stand-in: a logging middleware

A logger must know the status code that the handler wrote. Go's http.ResponseWriter does not expose it after the fact, so the stand-in wraps the writer to record it (Gin's own writer does this for you, which is why c.Writer.Status() exists). To keep the output stable, this version prints the line without the latency.

Go Stand-in: access log middleware

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Notice that /healthz produced no line because it was in the skip list, and that the logger sees the 418 and 404 statuses written deeper in the chain.

Stand-in: a recovery middleware

Now the safety net. The handler for /boom panics with a nil map write and a handler for /index goes out of range. The middleware recovers both and returns a JSON 500 without exposing the panic text.

Go Stand-in: recovering from panics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The last request shows the important point: after two panics the server is still healthy. The client sees only a generic message, while the panic text and (in Gin) the stack trace go to the server log.

Request IDs and correlating logs

When two users report errors at the same time, you need to tell their log lines apart. Add a request ID in a small middleware (we write one in Writing Custom Middleware), put it in the response header and include it in every log line and error response. The ID turns "something failed around 10:15" into a precise search.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does gin.Default() add compared to gin.New()?

    gin.Default() calls gin.New() and then Use(Logger(), Recovery()).
  2. 2. Why does the Logger run its output code after c.Next()?

    Only after the handlers finish are the status, size and duration known.
  3. 3. Which panic does Recovery NOT catch?

    Goroutines you start run outside the handler's call stack; they need their own defer and recover.
  4. 4. How do you stop /healthz from filling the access log?

    LoggerConfig.SkipPaths lists paths that are not logged.

Summary

  • gin.Default() = gin.New() + Logger + Recovery.
  • Logger writes status, latency, IP, method and path after the handler; customize with LoggerWithFormatter and LoggerWithConfig.
  • Recovery turns panics into a 500 and logs the stack; use CustomRecovery for a JSON response.
  • Panics in your own goroutines are not covered.
  • Keep secrets out of logs; add a request ID to correlate lines.

Next: Writing Custom Middleware builds request IDs, authentication and more.