mirror of
https://github.com/gofiber/fiber.git
synced 2025-05-31 11:52:41 +00:00
📝 docs: Document usage of Custom Tags in Logger middleware (#3446)
* 📝 docs: Update logger middleware documentation to include CustomTags for logging Request ID * 📚 docs: fix markdown lint errors
This commit is contained in:
parent
ab7f949382
commit
4aae3271af
@ -1841,7 +1841,7 @@ app.Get("/cbor", func(c fiber.Ctx) error {
|
||||
|
||||
### Links
|
||||
|
||||
Joins the links followed by the property to populate the response’s [Link](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link) HTTP header field.
|
||||
Joins the links followed by the property to populate the response’s [Link HTTP header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link) field.
|
||||
|
||||
```go title="Signature"
|
||||
func (c fiber.Ctx) Links(link ...string)
|
||||
@ -2040,7 +2040,7 @@ For sending multiple files from an embedded file system, [this functionality](..
|
||||
Sets the status code and the correct status message in the body if the response body is **empty**.
|
||||
|
||||
:::tip
|
||||
You can find all used status codes and messages [here](https://github.com/gofiber/fiber/blob/dffab20bcdf4f3597d2c74633a7705a517d2c8c2/utils.go#L183-L244).
|
||||
You can find all used status codes and messages [in the Fiber source code](https://github.com/gofiber/fiber/blob/dffab20bcdf4f3597d2c74633a7705a517d2c8c2/utils.go#L183-L244).
|
||||
:::
|
||||
|
||||
```go title="Signature"
|
||||
@ -2194,7 +2194,7 @@ app.Get("/world", func(c fiber.Ctx) error {
|
||||
|
||||
### Type
|
||||
|
||||
Sets the [Content-Type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type) HTTP header to the MIME type listed [here](https://github.com/nginx/nginx/blob/master/conf/mime.types) specified by the file **extension**.
|
||||
Sets the [Content-Type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type) HTTP header to the MIME type listed [in the Nginx MIME types configuration](https://github.com/nginx/nginx/blob/master/conf/mime.types) specified by the file **extension**.
|
||||
|
||||
:::info
|
||||
This method is **chainable**.
|
||||
|
@ -7,7 +7,7 @@ id: compress
|
||||
Compression middleware for [Fiber](https://github.com/gofiber/fiber) that will compress the response using `gzip`, `deflate`, `brotli`, and `zstd` compression depending on the [Accept-Encoding](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding) header.
|
||||
|
||||
:::note
|
||||
The compression middleware refrains from compressing bodies that are smaller than 200 bytes. This decision is based on the observation that, in such cases, the compressed size is likely to exceed the original size, making compression inefficient. [more](https://github.com/valyala/fasthttp/blob/497922a21ef4b314f393887e9c6147b8c3e3eda4/http.go#L1713-L1715)
|
||||
The compression middleware refrains from compressing bodies that are smaller than 200 bytes. This decision is based on the observation that, for small bodies, the compressed size is likely to exceed the original size, making compression inefficient and consuming unnecessary CPU time. [More details in fasthttp source](https://github.com/valyala/fasthttp/blob/497922a21ef4b314f393887e9c6147b8c3e3eda4/http.go#L1713-L1715).
|
||||
:::
|
||||
|
||||
## Signatures
|
||||
|
@ -41,10 +41,16 @@ app.Use(logger.New(logger.Config{
|
||||
}))
|
||||
|
||||
// Logging Request ID
|
||||
app.Use(requestid.New())
|
||||
app.Use(requestid.New()) // Ensure requestid middleware is used before the logger
|
||||
app.Use(logger.New(logger.Config{
|
||||
CustomTags: map[string]logger.LogFunc{
|
||||
"requestid": func(output logger.Buffer, c fiber.Ctx, data *logger.Data, extraParam string) (int, error) {
|
||||
return output.WriteString(requestid.FromContext(c))
|
||||
},
|
||||
},
|
||||
// For more options, see the Config section
|
||||
Format: "${pid} ${locals:requestid} ${status} - ${method} ${path}\n",
|
||||
// Use the custom tag ${requestid} as defined above.
|
||||
Format: "${pid} ${requestid} ${status} - ${method} ${path}\n",
|
||||
}))
|
||||
|
||||
// Changing TimeZone & TimeFormat
|
||||
|
@ -39,7 +39,7 @@ app.Post("/api/register", func(c fiber.Ctx) error {
|
||||
})
|
||||
```
|
||||
|
||||
<Reference id="use">**Use**</Reference>
|
||||
<Reference id="use">#Use</Reference>
|
||||
|
||||
Can be used for middleware packages and prefix catchers. These routes will only match the beginning of each path i.e. `/john` will match `/john/doe`, `/johnnnnn` etc
|
||||
|
||||
|
@ -26,8 +26,13 @@ Here's a quick overview of the changes in Fiber `v3`:
|
||||
- [🧰 Generic functions](#-generic-functions)
|
||||
- [📃 Log](#-log)
|
||||
- [🧬 Middlewares](#-middlewares)
|
||||
- [Important Change for Accessing Middleware Data](#important-change-for-accessing-middleware-data)
|
||||
- [Adaptor](#adaptor)
|
||||
- [Cache](#cache)
|
||||
- [CORS](#cors)
|
||||
- [CSRF](#csrf)
|
||||
- [Compression](#compression)
|
||||
- [EncryptCookie](#encryptcookie)
|
||||
- [Session](#session)
|
||||
- [Logger](#logger)
|
||||
- [Filesystem](#filesystem)
|
||||
@ -284,7 +289,7 @@ app.Route("/api").Route("/user/:id?")
|
||||
|
||||
</details>
|
||||
|
||||
[Here](./api/app#route) you can find more information.
|
||||
You can find more information about `app.Route` in the [API documentation](./api/app#route).
|
||||
|
||||
### Middleware registration
|
||||
|
||||
@ -816,6 +821,28 @@ app.Use(logger.New(logger.Config{
|
||||
|
||||
## 🧬 Middlewares
|
||||
|
||||
### Important Change for Accessing Middleware Data
|
||||
|
||||
In Fiber v3, many middlewares that previously set values in `c.Locals()` using string keys (e.g., `c.Locals("requestid")`) have been updated. To align with Go's context best practices and prevent key collisions, these middlewares now store their specific data in the request's context using unexported keys of custom types.
|
||||
|
||||
This means that directly accessing these values via `c.Locals("some_string_key")` will no longer work for such middleware-provided data.
|
||||
|
||||
**How to Access Middleware Data in v3:**
|
||||
|
||||
Each affected middleware now provides dedicated exported functions to retrieve its specific data from the context. You should use these functions instead of relying on string-based lookups in `c.Locals()`.
|
||||
|
||||
Examples include:
|
||||
|
||||
- `requestid.FromContext(c)`
|
||||
- `csrf.TokenFromContext(c)`
|
||||
- `csrf.HandlerFromContext(c)`
|
||||
- `session.FromContext(c)`
|
||||
- `basicauth.UsernameFromContext(c)`
|
||||
- `basicauth.PasswordFromContext(c)`
|
||||
- `keyauth.TokenFromContext(c)`
|
||||
|
||||
When used with the Logger middleware, the recommended approach is to use the `CustomTags` feature of the logger, which allows you to call these specific `FromContext` functions. See the [Logger](#logger) section for more details.
|
||||
|
||||
### Adaptor
|
||||
|
||||
The adaptor middleware has been significantly optimized for performance and efficiency. Key improvements include reduced response times, lower memory usage, and fewer memory allocations. These changes make the middleware more reliable and capable of handling higher loads effectively. Enhancements include the introduction of a `sync.Pool` for managing `fasthttp.RequestCtx` instances and better HTTP request and response handling between net/http and fasthttp contexts.
|
||||
@ -933,6 +960,79 @@ func main() {
|
||||
|
||||
</details>
|
||||
|
||||
#### Logging Middleware Values (e.g., Request ID)
|
||||
|
||||
In Fiber v3, middleware (like `requestid`) now stores values in the request context using unexported keys of custom types. This aligns with Go's context best practices to prevent key collisions between packages.
|
||||
|
||||
As a result, directly accessing these values using string keys with `c.Locals("your_key")` or in the logger format string with `${locals:your_key}` (e.g., `${locals:requestid}`) will no longer work for values set by such middleware.
|
||||
|
||||
**Recommended Solution: `CustomTags`**
|
||||
|
||||
The cleanest and most maintainable way to include these middleware-specific values in your logs is by using the `CustomTags` option in the logger middleware configuration. This allows you to define a custom function to retrieve the value correctly from the context.
|
||||
|
||||
<details>
|
||||
<summary>Example: Logging Request ID with CustomTags</summary>
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/gofiber/fiber/v3/middleware/logger"
|
||||
"github.com/gofiber/fiber/v3/middleware/requestid"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := fiber.New()
|
||||
|
||||
// Ensure requestid middleware is used before the logger
|
||||
app.Use(requestid.New())
|
||||
|
||||
app.Use(logger.New(logger.Config{
|
||||
CustomTags: map[string]logger.LogFunc{
|
||||
"requestid": func(output logger.Buffer, c fiber.Ctx, data *logger.Data, extraParam string) (int, error) {
|
||||
// Retrieve the request ID using the middleware's specific function
|
||||
return output.WriteString(requestid.FromContext(c))
|
||||
},
|
||||
},
|
||||
// Use the custom tag in your format string
|
||||
Format: "[${time}] ${ip} - ${requestid} - ${status} ${method} ${path}\n",
|
||||
}))
|
||||
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
return c.SendString("Hello, World!")
|
||||
})
|
||||
|
||||
app.Listen(":3000")
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
**Alternative: Manually Copying to `Locals`**
|
||||
|
||||
If you have existing logging patterns that rely on `c.Locals` or prefer to manage these values in `Locals` for other reasons, you can manually copy the value from the context to `c.Locals` in a preceding middleware:
|
||||
|
||||
<details>
|
||||
<summary>Example: Manually setting requestid in Locals</summary>
|
||||
|
||||
```go
|
||||
app.Use(requestid.New()) // Request ID middleware
|
||||
app.Use(func(c fiber.Ctx) error {
|
||||
// Manually copy the request ID to Locals
|
||||
c.Locals("requestid", requestid.FromContext(c))
|
||||
return c.Next()
|
||||
})
|
||||
app.Use(logger.New(logger.Config{
|
||||
// Now ${locals:requestid} can be used, but CustomTags is generally preferred
|
||||
Format: "[${time}] ${ip} - ${locals:requestid} - ${status} ${method} ${path}\n",
|
||||
}))
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
Both approaches ensure your logger can access these values while respecting Go's context practices.
|
||||
|
||||
The `Skip` is a function to determine if logging is skipped or written to `Stream`.
|
||||
|
||||
<details>
|
||||
@ -1060,10 +1160,16 @@ func main() {
|
||||
- [🚀 App](#-app-1)
|
||||
- [🗺 Router](#-router-1)
|
||||
- [🧠 Context](#-context-1)
|
||||
- [📎 Parser](#-parser)
|
||||
- [📎 Binding (was Parser)](#-parser)
|
||||
- [🔄 Redirect](#-redirect-1)
|
||||
- [🌎 Client package](#-client-package-1)
|
||||
- [🧬 Middlewares](#-middlewares-1)
|
||||
- [Important Change for Accessing Middleware Data](#important-change-for-accessing-middleware-data)
|
||||
- [CORS](#cors-1)
|
||||
- [CSRF](#csrf)
|
||||
- [Filesystem](#filesystem-1)
|
||||
- [Healthcheck](#healthcheck-1)
|
||||
- [Monitor](#monitor-1)
|
||||
|
||||
### 🚀 App
|
||||
|
||||
@ -1489,6 +1595,32 @@ DRAFT section
|
||||
|
||||
### 🧬 Middlewares
|
||||
|
||||
#### Important Change for Accessing Middleware Data
|
||||
|
||||
**Change:** In Fiber v2, some middlewares set data in `c.Locals()` using string keys (e.g., `c.Locals("requestid")`). In Fiber v3, to align with Go's context best practices and prevent key collisions, these middlewares now store their specific data in the request's context using unexported keys of custom types.
|
||||
|
||||
**Impact:** Directly accessing these middleware-provided values via `c.Locals("some_string_key")` will no longer work.
|
||||
|
||||
**Migration Action:**
|
||||
You must update your code to use the dedicated exported functions provided by each affected middleware to retrieve its data from the context.
|
||||
|
||||
**Examples of new helper functions to use:**
|
||||
|
||||
- `requestid.FromContext(c)`
|
||||
- `csrf.TokenFromContext(c)`
|
||||
- `csrf.HandlerFromContext(c)`
|
||||
- `session.FromContext(c)`
|
||||
- `basicauth.UsernameFromContext(c)`
|
||||
- `basicauth.PasswordFromContext(c)`
|
||||
- `keyauth.TokenFromContext(c)`
|
||||
|
||||
**For logging these values:**
|
||||
The recommended approach is to use the `CustomTags` feature of the Logger middleware, which allows you to call these specific `FromContext` functions. Refer to the [Logger section in "What's New"](#logger) for detailed examples.
|
||||
|
||||
:::note
|
||||
If you were manually setting and retrieving your own application-specific values in `c.Locals()` using string keys, that functionality remains unchanged. This change specifically pertains to how Fiber's built-in (and some contrib) middlewares expose their data.
|
||||
:::
|
||||
|
||||
#### CORS
|
||||
|
||||
The CORS middleware has been updated to use slices instead of strings for the `AllowOrigins`, `AllowMethods`, `AllowHeaders`, and `ExposeHeaders` fields. Here's how you can update your code:
|
||||
|
Loading…
x
Reference in New Issue
Block a user