Middleware in Go Fiber allows you to process requests before they reach your route handlers. In this tutorial, we'll focus on using the Logger middleware to log request details such as method, path, status, and response time.
Step 1: Install Logger Middleware
To use the Logger middleware, install the necessary package:
go get github.com/gofiber/fiber/v2/middleware/logger
This command installs the Logger middleware, which logs HTTP requests.
Step 2: Using Logger Middleware
The Logger middleware provides structured logging for incoming requests, helping with debugging and monitoring.
Create a new file main.go and add the following code:
package main
import (
"log"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/logger"
)
func main() {
app := fiber.New()
// Apply Logger middleware
app.Use(logger.New())
app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("Hello, Fiber with Logger!")
})
log.Fatal(app.Listen(":3000"))
}
Step 3: Run the Application
Start the server by running:
go run main.go
Now, when you access http://localhost:3000/, the terminal will log the request details:
10:17:25 | 200 | 12.49µs | 127.0.0.1 | GET | / | -
This helps track incoming requests and debug issues easily.
Step 4: Customizing Logger Middleware
You can customize the Logger middleware to change the log format and output. Here’s an example with custom configurations:
app.Use(logger.New(logger.Config{
Format: "${time} | ${status} | ${method} | ${path} | ${latency}\n",
}))
This will log requests in the format:
10:18:10 | 200 | GET | / | 4.069µs
The ${latency} field captures the request processing time, helping you identify performance bottlenecks.
There you go, that is how you can use logger middleware in Go Fiber. Thank you for reading, and have a nice day!
Top comments (0)