middleware/logger
import "github.com/gofiber/fiber/v3/middleware/logger"
Constants
Source: middleware/logger/format.go:5
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 = "{\"time\":\"${time}\",\"ip\":\"${ip}\",\"method\":\"${method}\",\"url\":\"${url}\",\"status\":${status},\"bytesSent\":${bytesSent}}\n"
// Elastic Common Schema (ECS) Log Format
ECSFormat = "{\"@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}\"}\n"
)Logger variables
Source: middleware/logger/tags.go:20
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"
)Variables
ConfigDefault is the default config
Source: middleware/logger/config.go:114
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
}ErrTagInvalid is returned by RegisterTag and panicked from MustRegisterTag when the supplied tag name or renderer is empty.
Source: middleware/logger/tags.go:62
var ErrTagInvalid = errors.New("logger: tag name and function are required")ErrUnknownTag indicates that the logger middleware was configured with a format that references a tag with no registered renderer.
Source: middleware/logger/errors.go:12
var ErrUnknownTag = errors.New("logger: unknown template tag")Functions
func LoggerToWriter[T any](logger fiberlog.AllLogger[T], level fiberlog.Level) io.Writer
Source: middleware/logger/utils.go:86
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 MustRegisterTag(tag string, fn LogFunc)
Source: middleware/logger/tags.go:88
MustRegisterTag registers a global logger middleware tag and panics on failure.
func New(config ...Config) fiber.Handler
Source: middleware/logger/logger.go:30
New creates a new middleware handler
func RegisterContextTag(name string, extract func(ctx any) string)
Source: middleware/logger/context_tag.go:48
RegisterContextTag registers a string-valued tag in both the logger middleware tag registry and the package-level fiberlog context tag registry, so that the same name can be used in a logger.Config.Format and in fiberlog.SetContextTemplate. extract receives the raw context value (fiber.Ctx, *fasthttp.RequestCtx, or context.Context) and returns the rendered string; an empty return renders nothing.
Re-registering a name replaces both renderers. Panics if name is empty or extract is nil — registration is expected at init time.
func RegisterTag(tag string, fn LogFunc) error
Source: middleware/logger/tags.go:75
RegisterTag registers a global logger middleware tag. Registered tags are available to logger middleware instances created after registration and can be overridden per instance with Config.CustomTags. Re-registering a tag replaces the existing tag function.
func SanitizeValue(s string) string
Source: middleware/logger/utils.go:216
SanitizeValue returns s with ASCII control bytes replaced by spaces, preserving horizontal tab. It is the control-byte scrubbing the built-in tags apply to request-derived values, exported so that code taking one of the paths that bypasses those tags can apply it too:
- a tag registered with RegisterTag, MustRegisterTag or RegisterContextTag
- an entry in Config.CustomTags
- a Config.LoggerFunc, which replaces the whole rendering pipeline
Any of those can write a value that reached the handler percent-decoded — a query parameter, a form field, a header — and an unscrubbed CR/LF there forges an extra access-log line.
Clean input, the overwhelmingly common case, is returned unchanged with no allocation. Only ASCII controls are replaced; bytes at or above 0x80 pass through, so a value that may carry C1 controls (U+0080–U+009F, including NEL U+0085) needs its own handling.
Types
type Buffer
Source: middleware/logger/config.go:108
Buffer abstracts the buffer operations used when rendering log entries.
type Buffer = logtemplate.Buffertype Config
Source: middleware/logger/config.go:13
Config defines the config for middleware.
type Config struct {
// TimeDone stops the background timestamp updater when it is closed.
//
// Optional. Default: nil
TimeDone <-chan 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)
// CustomTags defines per-middleware tag functions.
// CustomTags override built-in and globally registered tags with the same name.
//
// Optional. Default: nil
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 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
}Fields
TimeDone <-chan struct{}TimeDone stops the background timestamp updater when it is closed.
Optional. Default: nil
Stream io.WriterStream is a writer where logs are written
Default: os.Stdout
Next func(c fiber.Ctx) boolNext defines a function to skip this middleware when returned true.
Optional. Default: nil
Skip func(c fiber.Ctx) boolSkip is a function to determine if logging is skipped or written to Stream.
Optional. Default: nil
Done func(c fiber.Ctx, logString []byte)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
CustomTags map[string]LogFuncCustomTags defines per-middleware tag functions. CustomTags override built-in and globally registered tags with the same name.
Optional. Default: nil
BeforeHandlerFunc func(*Config)You can define specific things before returning the handler: colors, template, etc.
Optional. Default: beforeHandlerFunc
LoggerFunc func(c fiber.Ctx, data *Data, cfg *Config) errorYou 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
Format stringFormat 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 no format is specified, the default format is used: "[${time}] ${ip} ${status} - ${latency} ${method} ${path} ${error}"
TimeFormat stringTimeFormat https://programming.guide/go/format-parse-string-time-date-example.html
Optional. Default: 15:04:05
TimeZone stringTimeZone can be specified, such as "UTC" and "America/New_York" and "Asia/Chongqing", etc
Optional. Default: "Local"
TimeInterval time.DurationTimeInterval is the delay before the timestamp is updated
Optional. Default: 500 * time.Millisecond
DisableColors boolDisableColors defines if the logs output should be colorized
Default: false
ForceColors boolForceColors forces the colors to be enabled even if the output is not a terminal
Default: false
type Data
Source: middleware/logger/data.go:13
Data is a struct to define some variables to use in custom logger function. TemplateChain and LogFuncChain are compiled once per middleware instance and shared across requests; custom LoggerFunc implementations must treat them as read-only.
type Data struct {
Start time.Time
Stop time.Time
ChainErr error
Timestamp string
Pid string
ErrPaddingStr string
TemplateChain [][]byte
LogFuncChain []LogFunc
// contains filtered or unexported fields
}Fields
Start time.TimeStop time.TimeChainErr errorTimestamp stringPid stringErrPaddingStr stringTemplateChain [][]byteLogFuncChain []LogFunc
type LogFunc
Source: middleware/logger/config.go:111
LogFunc formats logging output using the provided buffer and request data.
type LogFunc = logtemplate.Func[fiber.Ctx, Data]type UnknownTagError
Source: middleware/logger/errors.go:19
UnknownTagError is the typed error panicked from New when Config.Format references an unknown tag. Tag is the offending tag including any parametric suffix; Param is the parameter portion when the tag was parametric (empty for bare tags); Hint, when non-empty, is a human- readable suggestion (e.g. parametric form for a likely-mistyped bare tag).
type UnknownTagError struct {
Tag string
Param string
Hint string
}Fields
Tag stringParam stringHint string