logger

package
v3.0.0 Latest Latest
Warning

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

Go to latest
Published: Feb 2, 2026 License: MIT Imports: 17 Imported by: 95

Documentation

Index

Constants

View Source
const (
	// Fiber's default logger
	DefaultFormat = "[${time}] ${ip} ${status} - ${latency} ${method} ${path} ${error}\n"
	// Apache Common Log Format (CLF)
	CommonFormat = "${ip} - - [${time}] \"${method} ${url} ${protocol}\" ${status} ${bytesSent}\n"
	// Apache Combined Log Format
	CombinedFormat = "${ip} - - [${time}] \"${method} ${url} ${protocol}\" ${status} ${bytesSent} \"${referer}\" \"${ua}\"\n"
	// JSON log formats
	JSONFormat = "" /* 133-byte string literal not displayed */
	// Elastic Common Schema (ECS) Log Format
	ECSFormat = "" /* 373-byte string literal not displayed */
)
View Source
const (
	TagPid               = "pid"
	TagTime              = "time"
	TagReferer           = "referer"
	TagProtocol          = "protocol"
	TagScheme            = "scheme"
	TagPort              = "port"
	TagIP                = "ip"
	TagIPs               = "ips"
	TagHost              = "host"
	TagMethod            = "method"
	TagPath              = "path"
	TagURL               = "url"
	TagUA                = "ua"
	TagLatency           = "latency"
	TagStatus            = "status"
	TagResBody           = "resBody"
	TagReqHeaders        = "reqHeaders"
	TagQueryStringParams = "queryParams"
	TagBody              = "body"
	TagBytesSent         = "bytesSent"
	TagBytesReceived     = "bytesReceived"
	TagRoute             = "route"
	TagError             = "error"
	TagReqHeader         = "reqHeader:"
	TagRespHeader        = "respHeader:"
	TagLocals            = "locals:"
	TagQuery             = "query:"
	TagForm              = "form:"
	TagCookie            = "cookie:"
	TagBlack             = "black"
	TagRed               = "red"
	TagGreen             = "green"
	TagYellow            = "yellow"
	TagBlue              = "blue"
	TagMagenta           = "magenta"
	TagCyan              = "cyan"
	TagWhite             = "white"
	TagReset             = "reset"
)

Logger variables

Variables

View Source
var ConfigDefault = Config{
	Next:              nil,
	Skip:              nil,
	Done:              nil,
	Format:            DefaultFormat,
	TimeFormat:        "15:04:05",
	TimeZone:          "Local",
	TimeInterval:      500 * time.Millisecond,
	Stream:            os.Stdout,
	BeforeHandlerFunc: beforeHandlerFunc,
	LoggerFunc:        defaultLoggerInstance,
	// contains filtered or unexported fields
}

ConfigDefault is the default config

View Source
var ErrTemplateParameterMissing = errors.New("logger: template parameter missing")

ErrTemplateParameterMissing indicates that a template parameter was referenced but not provided.

Functions

func LoggerToWriter

func LoggerToWriter[T any](logger fiberlog.AllLogger[T], level fiberlog.Level) io.Writer

LoggerToWriter is a helper function that returns an io.Writer that writes to a custom logger. You can integrate 3rd party loggers such as zerolog, logrus, etc. to logger middleware using this function.

Valid levels: fiberlog.LevelInfo, fiberlog.LevelTrace, fiberlog.LevelWarn, fiberlog.LevelDebug, fiberlog.LevelError

func New

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

New creates a new middleware handler

Types

type Buffer

type Buffer interface {
	Len() int
	ReadFrom(r io.Reader) (int64, error)
	WriteTo(w io.Writer) (int64, error)
	Bytes() []byte
	Write(p []byte) (int, error)
	WriteByte(c byte) error
	WriteString(s string) (int, error)
	Set(p []byte)
	SetString(s string)
	String() string
}

Buffer abstracts the buffer operations used when rendering log entries.

type Config

type Config struct {
	// Stream is a writer where logs are written
	//
	// Default: os.Stdout
	Stream io.Writer

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

	// Skip is a function to determine if logging is skipped or written to Stream.
	//
	// Optional. Default: nil
	Skip func(c fiber.Ctx) bool

	// Done is a function that is called after the log string for a request is written to Output,
	// and pass the log string as parameter.
	//
	// Optional. Default: nil
	Done func(c fiber.Ctx, logString []byte)

	// tagFunctions defines the custom tag action
	//
	// Optional. Default: map[string]LogFunc
	CustomTags map[string]LogFunc

	// You can define specific things before returning the handler: colors, template, etc.
	//
	// Optional. Default: beforeHandlerFunc
	BeforeHandlerFunc func(*Config)

	// You can use custom loggers with Fiber by using this field.
	// This field is really useful if you're using Zerolog, Zap, Logrus, apex/log etc.
	// If you don't define anything for this field, it'll use default logger of Fiber.
	//
	// Optional. Default: defaultLogger
	LoggerFunc func(c fiber.Ctx, data *Data, cfg *Config) error

	// Format defines the logging format for the middleware.
	//
	// You can customize the log output by defining a format string with placeholders
	// such as: ${time}, ${ip}, ${status}, ${method}, ${path}, ${latency}, ${error}, etc.
	// The full list of available placeholders can be found in 'tags.go' or at
	// 'https://docs.gofiber.io/api/middleware/logger/#constants'.
	//
	// Fiber provides predefined logging formats that can be used directly:
	//
	//   - DefaultFormat    → Uses the default log format: "[${time}] ${ip} ${status} - ${latency} ${method} ${path} ${error}"
	//   - CommonFormat     → Uses the Apache Common Log Format (CLF): "${ip} - - [${time}] \"${method} ${url} ${protocol}\" ${status} ${bytesSent}\n"
	//   - CombinedFormat   → Uses the Apache Combined Log Format: "${ip} - - [${time}] \"${method} ${url} ${protocol}\" ${status} ${bytesSent} \"${referer}\" \"${ua}\"\n"
	//   - JSONFormat      → Uses the JSON log format: "{\"time\":\"${time}\",\"ip\":\"${ip}\",\"method\":\"${method}\",\"url\":\"${url}\",\"status\":${status},\"bytesSent\":${bytesSent}}\n"
	//   - ECSFormat        → Uses the Elastic Common Schema (ECS) log format: {\"@timestamp\":\"${time}\",\"ecs\":{\"version\":\"1.6.0\"},\"client\":{\"ip\":\"${ip}\"},\"http\":{\"request\":{\"method\":\"${method}\",\"url\":\"${url}\",\"protocol\":\"${protocol}\"},\"response\":{\"status_code\":${status},\"body\":{\"bytes\":${bytesSent}}}},\"log\":{\"level\":\"INFO\",\"logger\":\"fiber\"},\"message\":\"${method} ${url} responded with ${status}\"}"
	// If both `Format` and `CustomFormat` are provided, the `CustomFormat` will be used, and the `Format` field will be ignored.
	// If no format is specified, the default format is used:
	// "[${time}] ${ip} ${status} - ${latency} ${method} ${path} ${error}"
	Format string

	// TimeFormat https://programming.guide/go/format-parse-string-time-date-example.html
	//
	// Optional. Default: 15:04:05
	TimeFormat string

	// TimeZone can be specified, such as "UTC" and "America/New_York" and "Asia/Chongqing", etc
	//
	// Optional. Default: "Local"
	TimeZone string

	// TimeInterval is the delay before the timestamp is updated
	//
	// Optional. Default: 500 * time.Millisecond
	TimeInterval time.Duration

	// DisableColors defines if the logs output should be colorized
	//
	// Default: false
	DisableColors bool

	// ForceColors forces the colors to be enabled even if the output is not a terminal
	//
	// Default: false
	ForceColors bool
	// contains filtered or unexported fields
}

Config defines the config for middleware.

type Data

type Data struct {
	Start         time.Time
	Stop          time.Time
	ChainErr      error
	Timestamp     atomic.Value
	Pid           string
	ErrPaddingStr string
	TemplateChain [][]byte
	LogFuncChain  []LogFunc
}

Data is a struct to define some variables to use in custom logger function.

type LogFunc

type LogFunc func(output Buffer, c fiber.Ctx, data *Data, extraParam string) (int, error)

LogFunc formats logging output using the provided buffer and request data.

Jump to

Keyboard shortcuts

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