DEV Community

Cover image for Using Logger Middleware in Go Fiber
luthfisauqi17
luthfisauqi17

Posted on

3 1 1

Using Logger Middleware in Go Fiber


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
Enter fullscreen mode Exit fullscreen mode

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"))
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Run the Application

Start the server by running:

go run main.go
Enter fullscreen mode Exit fullscreen mode

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 | / | -
Enter fullscreen mode Exit fullscreen mode

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",
}))
Enter fullscreen mode Exit fullscreen mode

This will log requests in the format:

10:18:10 | 200 | GET | / |       4.069µs
Enter fullscreen mode Exit fullscreen mode

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!

Heroku

Deploy with ease. Manage efficiently. Scale faster.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

DEV is better (more customized, reading settings like dark mode etc) when you're signed in!

Okay