Logger
适用于 Fiber 的记录器中间件,用于记录 HTTP 请求/响应详细信息。
签名
func New(config ...Config) fiber.Handler
示例
导入 Fiber Web 框架中包含的中间件包
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/logger"
)
提示
注册顺序起作用。只有在此之后注册的所有路由才会被记录。因此,中间件应该是最早注册的中间件之一。
在启动 Fiber 应用程序后,可以使用以下可能性
// Initialize default config
app.Use(logger.New())
// Or extend your config for customization
// Logging remote IP and Port
app.Use(logger.New(logger.Config{
Format: "[${ip}]:${port} ${status} - ${method} ${path}\n",
}))
// Logging 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",
}))
// Changing TimeZone & TimeFormat
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 Tags
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("it is a custom tag")
},
},
}))
// Callback after log is written
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 to default format
app.Use(logger.New(logger.Config{
DisableColors: true,
}))
配置
配置
属性 | 类型 | 说明 | 默认值 |
---|---|---|---|
下一个 | func(*fiber.Ctx) bool | Next 定义了一个函数,当返回 true 时跳过此中间件。 | nil |
Done | func(*fiber.Ctx, []byte) | Done 是一个函数,在将请求的日志字符串写入 Output 后调用,并将日志字符串作为参数传递。 | nil |
CustomTags | map[string]LogFunc | tagFunctions 定义自定义标签操作。 | map[string]LogFunc |
Format | string | Format 定义日志标签。 | ${time} | ${status} | ${latency} | ${ip} | ${method} | ${path} | ${error}\n |
TimeFormat | string | TimeFormat 定义日志时间戳的时间格式。 | 15:04:05 |
TimeZone | string | TimeZone 可以指定,例如“UTC”、“America/New_York”和“Asia/Chongqing”等 | "Local" |
TimeInterval | time.Duration | TimeInterval 是更新时间戳之前的延迟。 | 500 * time.Millisecond |
Output | io.Writer | Output 是写入日志的编写器。 | os.Stdout |
DisableColors | bool | DisableColors 定义日志输出是否应着色。 | false |
enableColors | bool | 日志输出中启用颜色的内部字段。(这不是用户可配置字段) | - |
enableLatency | bool | 日志中启用延迟测量的内部字段。(这不是用户可配置字段) | - |
timeZoneLocation | *time.Location | 时区位置的内部字段。(这不是用户可配置字段) | - |
默认配置
var ConfigDefault = Config{
Next: nil,
Done: nil,
Format: "${time} | ${status} | ${latency} | ${ip} | ${method} | ${path} | ${error}\n",
TimeFormat: "15:04:05",
TimeZone: "Local",
TimeInterval: 500 * time.Millisecond,
Output: os.Stdout,
DisableColors: false,
}
常量
// Logger variables
const (
TagPid = "pid"
TagTime = "time"
TagReferer = "referer"
TagProtocol = "protocol"
TagPort = "port"
TagIP = "ip"
TagIPs = "ips"
TagHost = "host"
TagMethod = "method"
TagPath = "path"
TagURL = "url"
TagUA = "ua"
TagLatency = "latency"
TagStatus = "status" // response status
TagResBody = "resBody" // response body
TagReqHeaders = "reqHeaders"
TagQueryStringParams = "queryParams" // request query parameters
TagBody = "body" // request body
TagBytesSent = "bytesSent"
TagBytesReceived = "bytesReceived"
TagRoute = "route"
TagError = "error"
// DEPRECATED: Use TagReqHeader instead
TagHeader = "header:" // request header
TagReqHeader = "reqHeader:" // request header
TagRespHeader = "respHeader:" // response header
TagQuery = "query:" // request query
TagForm = "form:" // request form
TagCookie = "cookie:" // request cookie
TagLocals = "locals:"
// colors
TagBlack = "black"
TagRed = "red"
TagGreen = "green"
TagYellow = "yellow"
TagBlue = "blue"
TagMagenta = "magenta"
TagCyan = "cyan"
TagWhite = "white"
TagReset = "reset"
)