Skip to main content
Version: Next

Zap

Release Discord Test

Zap logging support for Fiber.

Compatible with Fiber v3.

Go version support

We only support the latest two versions of Go. Visit https://go.dev/doc/devel/release for more information.

Install

go get -u github.com/gofiber/fiber/v3
go get -u github.com/gofiber/contrib/v3/zap
go get -u go.uber.org/zap

Signature

zap.New(config ...zap.Config) fiber.Handler

Config

PropertyTypeDescriptionDefault
Nextfunc(fiber.Ctx) boolDefine a function to skip this middleware when returned truenil
Logger*zap.LoggerAdd custom zap logger.zap.NewProduction()
Fields[]stringAdd fields that you want to see.[]string{"latency", "status", "method", "url"}
FieldsFuncfunc(fiber.Ctx) []zap.FieldDefine a function to add custom fields.nil
Messages[]stringCustom response messages.[]string{"Server error", "Client error", "Success"}
Levels[]zapcore.LevelCustom response levels.[]zapcore.Level{zapcore.ErrorLevel, zapcore.WarnLevel, zapcore.InfoLevel}
SkipURIs[]stringSkip logging these URI.[]string{}
GetResBodyfunc(c fiber.Ctx) []byteDefine a function to get response body when return non-nil.
eg: When use compress middleware, resBody is unreadable. you can set GetResBody func to get readable resBody.
nil

Example

package main

import (
"log"

middleware "github.com/gofiber/contrib/v3/zap"
"github.com/gofiber/fiber/v3"
"go.uber.org/zap"
)

func main() {
app := fiber.New()
logger, _ := zap.NewProduction()
defer logger.Sync()

app.Use(middleware.New(middleware.Config{
Logger: logger,
}))

app.Get("/", func(c fiber.Ctx) error {
return c.SendString("Hello, World!")
})

log.Fatal(app.Listen(":3000"))
}

NewLogger

Signature

zap.NewLogger(config ...zap.LoggerConfig) *zap.LoggerConfig

LoggerConfig

PropertyTypeDescriptionDefault
CoreConfigs[]CoreConfigDefine Config for zapcorezap.LoggerConfigDefault
SetLogger*zap.LoggerAdd custom zap logger. if not nil, ZapOptions, CoreConfigs, SetLevel, SetOutput will be ignored.nil
ExtraKeys[]stringAllow users log extra values from context.[]string{}
ZapOptions[]zap.OptionAllow users to configure the zap.Option supplied by zap.[]zap.Option{}

Example

package main

import (
"context"

middleware "github.com/gofiber/contrib/v3/zap"
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/log"
)

func main() {
app := fiber.New()
logger := middleware.NewLogger(middleware.LoggerConfig{
ExtraKeys: []string{"request_id"},
})
log.SetLogger(logger)
defer logger.Sync()

app.Use(func(c fiber.Ctx) error {
ctx := context.WithValue(c.UserContext(), "request_id", "123")
c.SetUserContext(ctx)
return c.Next()
})
app.Get("/", func(c fiber.Ctx) error {
log.WithContext(c.UserContext()).Info("Hello, World!")
return c.SendString("Hello, World!")
})
log.Fatal(app.Listen(":3000"))
}