Logger
A middleware for Fiber that is used to log detailed information about HTTP requests and responses.
Interface
func New(config ...Config) fiber.Handler
Example
Import the middleware package of the Fiber web framework:
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/logger"
)
Note: The order of registration is crucial. Only routes registered after this middleware will be logged. Therefore, this middleware should be one of the first to be registered.
After initializing the Fiber application, it is possible to register the middleware in the following ways:
// Initialize with default configuration
app.Use(logger.New())
// Or customize the configuration
// Log remote IP and port
app.Use(logger.New(logger.Config{
Format: "[${ip}]:${port} ${status} - ${method} ${path}\n",
}))
// Log request ID
app.Use(requestid.New())
app.Use(logger.New(logger.Config{
// For more options, see the Config section
Format: "${pid} ${locals:requestid} ${status} - ${method} ${path}\n",
}))
// Change time zone and time format
app.Use(logger.New(logger.Config{
Format: "${pid} ${status} - ${method} ${path}\n",
TimeFormat: "02-Jan-2006",
TimeZone: "America/New_York",
}))
// Custom file writer
file, err := os.OpenFile("./123.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Fatalf("error opening file: %v", err)
}
defer file.Close()
app.Use(logger.New(logger.Config{
Output: file,
}))
// Add custom tag
app.Use(logger.New(logger.Config{
CustomTags: map[string]logger.LogFunc{
"custom_tag": func(output logger.Buffer, c *fiber.Ctx, data *logger.Data, extraParam string) (int, error) {
return output.WriteString("This is a custom tag")
},
},
}))
// Callback function after logging
app.Use(logger.New(logger.Config{
TimeFormat: time.RFC3339Nano,
TimeZone: "Asia/Shanghai",
Done: func(c *fiber.Ctx, logString []byte) {
if c.Response().StatusCode() != fiber.StatusOK {
reporter.SendToSlack(logString)
}
},
}))
// Disable colors when outputting in the default format
app.Use(logger.New(logger.Config{
DisableColors: true,
}))
Configuration
Property | Type | Description | Default Value |
---|---|---|---|
Next | func(*fiber.Ctx) bool |
Next defines a function that skips the middleware when it returns true. | nil |
Done | func(*fiber.Ctx, []byte) |
Done is a function that is called after writing the request's log string to Output, with the log string passed as a parameter. | nil |
CustomTags | map[string]LogFunc |
tagFunctions defines custom tag operations. | map[string]LogFunc |
Format | string |
Format defines the log tags. | [${time}] ${status} - ${latency} ${method} ${path}\n |
TimeFormat | string |
TimeFormat defines the time format of the log timestamp. | 15:04:05 |
TimeZone | string |
TimeZone can be specified as "UTC", "America/New_York", "Asia/Chongqing", etc. | "Local" |
TimeInterval | time.Duration |
TimeInterval is the delay time before updating the timestamp. | 500 * time.Millisecond |
Output | io.Writer |
Output is a writer used to write logs. | os.Stdout |
DisableColors | bool |
DisableColors defines whether the log output should be colored. | false |
enableColors | bool |
Internal field to enable colors in log output. (This is not a configurable field) | - |
enableLatency | bool |
Internal field to enable latency measurement in logs. (This is not a configurable field) | - |
timeZoneLocation | *time.Location |
Internal field for the time zone location. (This is not a configurable field) | - |
Default Configuration
var ConfigDefault = Config{
Next: nil,
Done: nil,
Format: "[${time}] ${status} - ${latency} ${method} ${path}\n",
TimeFormat: "15:04:05",
TimeZone: "Local",
TimeInterval: 500 * time.Millisecond,
Output: os.Stdout,
DisableColors: false,
}
Constants
// Logger variables
const (
TagPid = "pid" // Process ID
TagTime = "time" // Time
TagReferer = "referer" // Referrer
TagProtocol = "protocol" // Protocol
TagPort = "port" // Port
TagIP = "ip" // IP Address
TagIPs = "ips" // IP Addresses
TagHost = "host" // Host
TagMethod = "method" // Request Method
TagPath = "path" // Path
TagURL = "url" // URL
TagUA = "ua" // User Agent
TagLatency = "latency" // Latency
TagStatus = "status" // Response Status
TagResBody = "resBody" // Response Body
TagReqHeaders = "reqHeaders" // Request Headers
TagQueryStringParams = "queryParams" // Query Parameters
TagBody = "body" // Request Body
TagBytesSent = "bytesSent" // Bytes Sent
TagBytesReceived = "bytesReceived" // Bytes Received
TagRoute = "route" // Route
TagError = "error" // Error
// Deprecated: Use TagReqHeader instead
TagHeader = "header:" // Request Header
TagReqHeader = "reqHeader:" // Request Header
TagRespHeader = "respHeader:" // Response Header
TagQuery = "query:" // Query
TagForm = "form:" // Form
TagCookie = "cookie:" // Cookie
TagLocals = "locals:" // Local Variables
// Colors
TagBlack = "black" // Black
TagRed = "red" // Red
TagGreen = "green" // Green
TagYellow = "yellow" // Yellow
TagBlue = "blue" // Blue
TagMagenta = "magenta" // Magenta
TagCyan = "cyan" // Cyan
TagWhite = "white" // White
TagReset = "reset" // Reset Color
)