fiberzap

package module
v2.1.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 19, 2024 License: MIT Imports: 11 Imported by: 16

README


id: fiberzap

Fiberzap

Release Discord Test Security Linter

Zap logging support for Fiber.

Note: Requires Go 1.19 and above

Install

This middleware supports Fiber v2.

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

Signature

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

Config

Property Type Description Default
Next func(*Ctx) bool Define a function to skip this middleware when returned true nil
Logger *zap.Logger Add custom zap logger. zap.NewDevelopment()
Fields []string Add fields what you want see. []string{"latency", "status", "method", "url"}
FieldsFunc []zap.Field Define a function to add custom fields. nil
Messages []string Custom response messages. []string{"Server error", "Client error", "Success"}
Levels []zapcore.Level Custom response levels. []zapcore.Level{zapcore.ErrorLevel, zapcore.WarnLevel, zapcore.InfoLevel}
SkipURIs []string Skip logging these URI. []string{}
GetResBody func(c *fiber.Ctx) []byte Define 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"

    "github.com/gofiber/fiber/v2"
    "github.com/gofiber/contrib/fiberzap/v2"
    "go.uber.org/zap"
)

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

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

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

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

NewLogger

Signature

fiberzap.NewLogger(config ...fiberzap.LoggerConfig) *fiberzap.LoggerConfig

LoggerConfig

Property Type Description Default
CoreConfigs []CoreConfig Define Config for zapcore fiberzap.LoggerConfigDefault
SetLogger *zap.Logger Add custom zap logger. if not nil, ZapOptions, CoreConfigs, SetLevel, SetOutput will be ignored. nil
ExtraKeys []string Allow users log extra values from context. []string{}
ZapOptions []zap.Option Allow users to configure the zap.Option supplied by zap. []zap.Option{}

Example

package main

import (
	"context"
	"github.com/gofiber/contrib/fiberzap/v2"
	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/log"
)

func main() {
    app := fiber.New()
    log.SetLogger(fiberzap.NewLogger(fiberzap.LoggerConfig{
        ExtraKeys: []string{"request_id"},
    }))
    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"))
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ConfigDefault = Config{
	Next:       nil,
	Logger:     logger,
	Fields:     []string{"ip", "latency", "status", "method", "url"},
	FieldsFunc: nil,
	Messages:   []string{"Server error", "Client error", "Success"},
	Levels:     []zapcore.Level{zapcore.ErrorLevel, zapcore.WarnLevel, zapcore.InfoLevel},
}

ConfigDefault is the default config

View Source
var LoggerConfigDefault = LoggerConfig{
	CoreConfigs: []CoreConfig{
		{
			Encoder:      zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()),
			WriteSyncer:  zapcore.AddSync(os.Stdout),
			LevelEncoder: zap.NewAtomicLevelAt(zap.InfoLevel),
		},
	},
	ZapOptions: []zap.Option{
		zap.AddCaller(),
		zap.AddCallerSkip(3),
	},
}

LoggerConfigDefault is the default config

Functions

func New

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

New creates a new middleware handler

Types

type Config

type Config struct {
	// Next defines a function to skip this middleware when returned true.
	//
	// Optional. Default: nil
	Next func(c *fiber.Ctx) bool

	// SkipBody defines a function to skip log  "body" field when returned true.
	//
	// Optional. Default: nil
	SkipBody func(c *fiber.Ctx) bool

	// SkipResBody defines a function to skip log  "resBody" field when returned true.
	//
	// Optional. Default: nil
	SkipResBody func(c *fiber.Ctx) bool

	// GetResBody defines a function to get ResBody.
	//  eg: when use compress middleware, resBody is unreadable. you can set GetResBody func to get readable resBody.
	//
	// Optional. Default: nil
	GetResBody func(c *fiber.Ctx) []byte

	// Skip logging for these uri
	//
	// Optional. Default: nil
	SkipURIs []string

	// Add custom zap logger.
	//
	// Optional. Default: zap.NewProduction()\n
	Logger *zap.Logger

	// Add fields what you want see.
	//
	// Optional. Default: {"ip", "latency", "status", "method", "url"}
	Fields []string

	// FieldsFunc defines a function to return custom zap fields to append to the log.
	//
	// Optional. Default: nil
	FieldsFunc func(c *fiber.Ctx) []zap.Field

	// Custom response messages.
	// Response codes >= 500 will be logged with Messages[0].
	// Response codes >= 400 will be logged with Messages[1].
	// Other response codes will be logged with Messages[2].
	// You can specify less, than 3 messages, but you must specify at least 1.
	// Specifying more than 3 messages is useless.
	//
	// Optional. Default: {"Server error", "Client error", "Success"}
	Messages []string

	// Custom response levels.
	// Response codes >= 500 will be logged with Levels[0].
	// Response codes >= 400 will be logged with Levels[1].
	// Other response codes will be logged with Levels[2].
	// You can specify less, than 3 levels, but you must specify at least 1.
	// Specifying more than 3 levels is useless.
	//
	// Optional. Default: {zapcore.ErrorLevel, zapcore.WarnLevel, zapcore.InfoLevel}
	Levels []zapcore.Level
}

Config defines the config for middleware.

type CoreConfig

type CoreConfig struct {
	Encoder      zapcore.Encoder
	WriteSyncer  zapcore.WriteSyncer
	LevelEncoder zapcore.LevelEnabler
}

type LoggerConfig

type LoggerConfig struct {
	// CoreConfigs allows users to configure Encoder, WriteSyncer, LevelEnabler configuration items provided by zapcore
	//
	// Optional. Default: LoggerConfigDefault
	CoreConfigs []CoreConfig
	// ZapOptions allow users to configure the zap.Option supplied by zap.
	//
	// Optional. Default: []zap.Option
	ZapOptions []zap.Option

	// ExtraKeys allow users log extra values from context
	//
	// Optional. Default: []string
	ExtraKeys []string

	// SetLogger sets *zap.Logger for fiberlog, if set, ZapOptions, CoreConfigs, SetLevel, SetOutput will be ignored
	//
	// Optional. Default: nil
	SetLogger *zap.Logger
	// contains filtered or unexported fields
}

func NewLogger

func NewLogger(config ...LoggerConfig) *LoggerConfig

NewLogger creates a new zap logger adapter for fiberlog

func (*LoggerConfig) Debug

func (l *LoggerConfig) Debug(v ...interface{})

func (*LoggerConfig) Debugf

func (l *LoggerConfig) Debugf(format string, v ...interface{})

func (*LoggerConfig) Debugw

func (l *LoggerConfig) Debugw(msg string, keysAndValues ...interface{})

func (*LoggerConfig) Error

func (l *LoggerConfig) Error(v ...interface{})

func (*LoggerConfig) Errorf

func (l *LoggerConfig) Errorf(format string, v ...interface{})

func (*LoggerConfig) Errorw

func (l *LoggerConfig) Errorw(msg string, keysAndValues ...interface{})

func (*LoggerConfig) Fatal

func (l *LoggerConfig) Fatal(v ...interface{})

func (*LoggerConfig) Fatalf

func (l *LoggerConfig) Fatalf(format string, v ...interface{})

func (*LoggerConfig) Fatalw

func (l *LoggerConfig) Fatalw(msg string, keysAndValues ...interface{})

func (*LoggerConfig) Info

func (l *LoggerConfig) Info(v ...interface{})

func (*LoggerConfig) Infof

func (l *LoggerConfig) Infof(format string, v ...interface{})

func (*LoggerConfig) Infow

func (l *LoggerConfig) Infow(msg string, keysAndValues ...interface{})

func (*LoggerConfig) Log

func (l *LoggerConfig) Log(level fiberlog.Level, kvs ...interface{})

func (*LoggerConfig) Logf

func (l *LoggerConfig) Logf(level fiberlog.Level, format string, kvs ...interface{})

func (*LoggerConfig) Logger

func (l *LoggerConfig) Logger() *zap.Logger

Logger returns the underlying *zap.Logger when not using SetLogger

func (*LoggerConfig) Logw

func (l *LoggerConfig) Logw(level fiberlog.Level, msg string, keyvals ...interface{})

func (*LoggerConfig) Panic

func (l *LoggerConfig) Panic(v ...interface{})

func (*LoggerConfig) Panicf

func (l *LoggerConfig) Panicf(format string, v ...interface{})

func (*LoggerConfig) Panicw

func (l *LoggerConfig) Panicw(msg string, keysAndValues ...interface{})

func (*LoggerConfig) SetLevel

func (l *LoggerConfig) SetLevel(lv fiberlog.Level)

func (*LoggerConfig) SetOutput

func (l *LoggerConfig) SetOutput(w io.Writer)

SetOutput sets the output destination for the logger.

func (*LoggerConfig) Sync

func (l *LoggerConfig) Sync() error

Sync flushes any buffered log entries.

func (*LoggerConfig) Trace

func (l *LoggerConfig) Trace(v ...interface{})

func (*LoggerConfig) Tracef

func (l *LoggerConfig) Tracef(format string, v ...interface{})

func (*LoggerConfig) Tracew

func (l *LoggerConfig) Tracew(msg string, keysAndValues ...interface{})

func (*LoggerConfig) Warn

func (l *LoggerConfig) Warn(v ...interface{})

func (*LoggerConfig) Warnf

func (l *LoggerConfig) Warnf(format string, v ...interface{})

func (*LoggerConfig) Warnw

func (l *LoggerConfig) Warnw(msg string, keysAndValues ...interface{})

func (*LoggerConfig) WithContext

func (l *LoggerConfig) WithContext(ctx context.Context) fiberlog.CommonLogger

WithContext returns a new LoggerConfig with extra fields from context

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL