DEV Community

Cover image for Using Logger Middleware in Go Fiber
luthfisauqi17
luthfisauqi17

Posted on

2

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!

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay