Skip to content

Commit a4121ce

Browse files
sixcolorsefectn
authored andcommitted
πŸ“ docs: Document usage of Custom Tags in Logger middleware (gofiber#3446)
* πŸ“ docs: Update logger middleware documentation to include CustomTags for logging Request ID * πŸ“š docs: fix markdown lint errors
1 parent 0dacc0a commit a4121ce

File tree

5 files changed

+147
-9
lines changed

5 files changed

+147
-9
lines changed

β€Ždocs/api/ctx.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1841,7 +1841,7 @@ app.Get("/cbor", func(c fiber.Ctx) error {
18411841

18421842
### Links
18431843

1844-
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.
1844+
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.
18451845

18461846
```go title="Signature"
18471847
func (c fiber.Ctx) Links(link ...string)
@@ -2040,7 +2040,7 @@ For sending multiple files from an embedded file system, [this functionality](..
20402040
Sets the status code and the correct status message in the body if the response body is **empty**.
20412041

20422042
:::tip
2043-
You can find all used status codes and messages [here](https://github.com/gofiber/fiber/blob/dffab20bcdf4f3597d2c74633a7705a517d2c8c2/utils.go#L183-L244).
2043+
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).
20442044
:::
20452045

20462046
```go title="Signature"
@@ -2194,7 +2194,7 @@ app.Get("/world", func(c fiber.Ctx) error {
21942194

21952195
### Type
21962196

2197-
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**.
2197+
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**.
21982198

21992199
:::info
22002200
This method is **chainable**.

β€Ždocs/middleware/compress.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ id: compress
77
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.
88

99
:::note
10-
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)
10+
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).
1111
:::
1212

1313
## Signatures

β€Ždocs/middleware/logger.md

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,10 +41,16 @@ app.Use(logger.New(logger.Config{
4141
}))
4242

4343
// Logging Request ID
44-
app.Use(requestid.New())
44+
app.Use(requestid.New()) // Ensure requestid middleware is used before the logger
4545
app.Use(logger.New(logger.Config{
46+
CustomTags: map[string]logger.LogFunc{
47+
"requestid": func(output logger.Buffer, c fiber.Ctx, data *logger.Data, extraParam string) (int, error) {
48+
return output.WriteString(requestid.FromContext(c))
49+
},
50+
},
4651
// For more options, see the Config section
47-
Format: "${pid} ${locals:requestid} ${status} - ${method} ${path}\n",
52+
// Use the custom tag ${requestid} as defined above.
53+
Format: "${pid} ${requestid} ${status} - ${method} ${path}\n",
4854
}))
4955

5056
// Changing TimeZone & TimeFormat

β€Ždocs/partials/routing/handler.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ app.Post("/api/register", func(c fiber.Ctx) error {
3939
})
4040
```
4141

42-
<Reference id="use">**Use**</Reference>
42+
<Reference id="use">#Use</Reference>
4343

4444
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
4545

β€Ždocs/whats_new.md

Lines changed: 134 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,13 @@ Here's a quick overview of the changes in Fiber `v3`:
2626
- [🧰 Generic functions](#-generic-functions)
2727
- [πŸ“ƒ Log](#-log)
2828
- [🧬 Middlewares](#-middlewares)
29+
- [Important Change for Accessing Middleware Data](#important-change-for-accessing-middleware-data)
30+
- [Adaptor](#adaptor)
31+
- [Cache](#cache)
2932
- [CORS](#cors)
3033
- [CSRF](#csrf)
34+
- [Compression](#compression)
35+
- [EncryptCookie](#encryptcookie)
3136
- [Session](#session)
3237
- [Logger](#logger)
3338
- [Filesystem](#filesystem)
@@ -284,7 +289,7 @@ app.Route("/api").Route("/user/:id?")
284289

285290
</details>
286291

287-
[Here](./api/app#route) you can find more information.
292+
You can find more information about `app.Route` in the [API documentation](./api/app#route).
288293

289294
### Middleware registration
290295

@@ -816,6 +821,28 @@ app.Use(logger.New(logger.Config{
816821

817822
## 🧬 Middlewares
818823

824+
### Important Change for Accessing Middleware Data
825+
826+
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.
827+
828+
This means that directly accessing these values via `c.Locals("some_string_key")` will no longer work for such middleware-provided data.
829+
830+
**How to Access Middleware Data in v3:**
831+
832+
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()`.
833+
834+
Examples include:
835+
836+
- `requestid.FromContext(c)`
837+
- `csrf.TokenFromContext(c)`
838+
- `csrf.HandlerFromContext(c)`
839+
- `session.FromContext(c)`
840+
- `basicauth.UsernameFromContext(c)`
841+
- `basicauth.PasswordFromContext(c)`
842+
- `keyauth.TokenFromContext(c)`
843+
844+
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.
845+
819846
### Adaptor
820847

821848
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() {
933960

934961
</details>
935962

963+
#### Logging Middleware Values (e.g., Request ID)
964+
965+
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.
966+
967+
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.
968+
969+
**Recommended Solution: `CustomTags`**
970+
971+
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.
972+
973+
<details>
974+
<summary>Example: Logging Request ID with CustomTags</summary>
975+
976+
```go
977+
package main
978+
979+
import (
980+
"github.com/gofiber/fiber/v3"
981+
"github.com/gofiber/fiber/v3/middleware/logger"
982+
"github.com/gofiber/fiber/v3/middleware/requestid"
983+
)
984+
985+
func main() {
986+
app := fiber.New()
987+
988+
// Ensure requestid middleware is used before the logger
989+
app.Use(requestid.New())
990+
991+
app.Use(logger.New(logger.Config{
992+
CustomTags: map[string]logger.LogFunc{
993+
"requestid": func(output logger.Buffer, c fiber.Ctx, data *logger.Data, extraParam string) (int, error) {
994+
// Retrieve the request ID using the middleware's specific function
995+
return output.WriteString(requestid.FromContext(c))
996+
},
997+
},
998+
// Use the custom tag in your format string
999+
Format: "[${time}] ${ip} - ${requestid} - ${status} ${method} ${path}\n",
1000+
}))
1001+
1002+
app.Get("/", func(c fiber.Ctx) error {
1003+
return c.SendString("Hello, World!")
1004+
})
1005+
1006+
app.Listen(":3000")
1007+
}
1008+
```
1009+
1010+
</details>
1011+
1012+
**Alternative: Manually Copying to `Locals`**
1013+
1014+
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:
1015+
1016+
<details>
1017+
<summary>Example: Manually setting requestid in Locals</summary>
1018+
1019+
```go
1020+
app.Use(requestid.New()) // Request ID middleware
1021+
app.Use(func(c fiber.Ctx) error {
1022+
// Manually copy the request ID to Locals
1023+
c.Locals("requestid", requestid.FromContext(c))
1024+
return c.Next()
1025+
})
1026+
app.Use(logger.New(logger.Config{
1027+
// Now ${locals:requestid} can be used, but CustomTags is generally preferred
1028+
Format: "[${time}] ${ip} - ${locals:requestid} - ${status} ${method} ${path}\n",
1029+
}))
1030+
```
1031+
1032+
</details>
1033+
1034+
Both approaches ensure your logger can access these values while respecting Go's context practices.
1035+
9361036
The `Skip` is a function to determine if logging is skipped or written to `Stream`.
9371037

9381038
<details>
@@ -1060,10 +1160,16 @@ func main() {
10601160
- [πŸš€ App](#-app-1)
10611161
- [πŸ—Ί Router](#-router-1)
10621162
- [🧠 Context](#-context-1)
1063-
- [πŸ“Ž Parser](#-parser)
1163+
- [πŸ“Ž Binding (was Parser)](#-parser)
10641164
- [πŸ”„ Redirect](#-redirect-1)
10651165
- [🌎 Client package](#-client-package-1)
10661166
- [🧬 Middlewares](#-middlewares-1)
1167+
- [Important Change for Accessing Middleware Data](#important-change-for-accessing-middleware-data)
1168+
- [CORS](#cors-1)
1169+
- [CSRF](#csrf)
1170+
- [Filesystem](#filesystem-1)
1171+
- [Healthcheck](#healthcheck-1)
1172+
- [Monitor](#monitor-1)
10671173

10681174
### πŸš€ App
10691175

@@ -1497,6 +1603,32 @@ DRAFT section
14971603

14981604
### 🧬 Middlewares
14991605

1606+
#### Important Change for Accessing Middleware Data
1607+
1608+
**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.
1609+
1610+
**Impact:** Directly accessing these middleware-provided values via `c.Locals("some_string_key")` will no longer work.
1611+
1612+
**Migration Action:**
1613+
You must update your code to use the dedicated exported functions provided by each affected middleware to retrieve its data from the context.
1614+
1615+
**Examples of new helper functions to use:**
1616+
1617+
- `requestid.FromContext(c)`
1618+
- `csrf.TokenFromContext(c)`
1619+
- `csrf.HandlerFromContext(c)`
1620+
- `session.FromContext(c)`
1621+
- `basicauth.UsernameFromContext(c)`
1622+
- `basicauth.PasswordFromContext(c)`
1623+
- `keyauth.TokenFromContext(c)`
1624+
1625+
**For logging these values:**
1626+
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.
1627+
1628+
:::note
1629+
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.
1630+
:::
1631+
15001632
#### CORS
15011633
15021634
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:

0 commit comments

Comments
Β (0)