You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Context binding adds request-specific data for easier tracing.
208
+
Context binding can render request-specific data for easier tracing. The default context format is `log.DefaultFormat` (the empty string), so `log.WithContext(ctx)` adds no fields until you configure a format with `log.SetContextTemplate` (or its `MustSetContextTemplate` panic-on-error variant).
209
+
210
+
`SetContextTemplate` configures Fiber's built-in default logger. Custom loggers registered with `SetLogger` keep full control over their own `WithContext` behavior and should implement equivalent enrichment themselves when needed.
Middleware that stores request values registers its log context tags automatically. For example, importing `requestid` makes `${requestid}` and `${request-id}` available; the actual value is filled in once `requestid.New()` runs in your handler stack. Until then the tag renders as an empty string, so a format that references `${requestid}` still compiles without `requestid.New()` in the chain.
230
+
231
+
Use `log.WithContext(c)` inside handlers when you want tags to read values stored by Fiber middleware. Passing `c.Context()` only exposes values propagated into the standard request context.
232
+
233
+
:::tip
234
+
Cross-reference: the access-log integration uses the same tag names — see [middleware/logger](../middleware/logger.md#config) for the request-time format.
235
+
:::
236
+
237
+
### Glossary
238
+
239
+
-**Format** — the string with `${...}` placeholders, e.g. `"[${requestid}] "`.
240
+
-**Template** — the compiled, reusable form of a format produced by `SetContextTemplate`.
241
+
-**Tag** — a single `${name}` (bare) or `${name:param}` (parametric) placeholder inside a format.
242
+
243
+
### Signatures
244
+
245
+
```go
246
+
// Configure the active context template (or pass log.ContextConfig{} to disable).
247
+
funcSetContextTemplate(configContextConfig) error
248
+
func MustSetContextTemplate(config ContextConfig)
249
+
250
+
// Register a tag globally; the new renderer becomes available to subsequent
251
+
// SetContextTemplate calls. The reserved TagContextValue ("value:") name
|`RequestIDFormat`|`"[${requestid}] "`| Prepends the request ID when the requestid middleware is used. |
285
+
|`KeyValueFormat`|`"request-id=${request-id} username=${username} api-key=${api-key} csrf-token=${csrf-token} session-id=${session-id} "`| Prepends common middleware context values as key/value fields. Sensitive values are redacted by the registering middleware. |
|`${username}`|`basicauth` middleware — written **in clear text** for audit-log use cases. Avoid this tag if your usernames are PII. |
293
+
|`${api-key}`|`keyauth` middleware, redacted to a 4-byte prefix |
294
+
|`${csrf-token}`|`csrf` middleware, redacted to a 4-byte prefix |
295
+
|`${session-id}`|`session` middleware, redacted to a 4-byte prefix |
296
+
|`${value:key}`| Any bound value with `Value(key)` or `UserValue(key)` lookup methods |
297
+
298
+
:::caution
299
+
`${value:KEY}` looks up arbitrary context values. CR, LF, NUL, and other ASCII control bytes (except tab) are replaced with spaces before they reach the log line, so attacker-controlled values cannot forge log lines via header smuggling. The lookup still writes the value verbatim apart from that scrub — strip or hash sensitive fields before storing them on the context if you do not want them in operator logs.
300
+
:::
301
+
302
+
### Custom Context Tags
303
+
304
+
Register custom tags with `log.RegisterContextTag`, then reference them from a format passed to `SetContextTemplate`. The built-in `${value:key}` tag is reserved for context-value lookups and cannot be overridden.
Register tags **before** referencing them in `SetContextTemplate`. Compiling a format that references an unregistered name returns `*logtemplate.UnknownTagError` (or panics from `MustSetContextTemplate`).
Some Fiber middleware registers logger middleware tags automatically. Register the producing middleware before `logger.New()` and then use the tag in `Format`.
The logger middleware resolves tags in this order:
129
+
130
+
1. Built-in logger tags, such as `${method}`, `${path}`, and `${status}`.
131
+
2. Globally registered tags from Fiber middleware or `logger.RegisterTag`.
132
+
3.`Config.CustomTags`, which override tags with the same name for that logger instance.
133
+
134
+
The following tags are registered by Fiber middleware when the middleware is initialized:
135
+
136
+
| Tag | Registered by | Value |
137
+
| :-- | :------------ | :---- |
138
+
|`${requestid}` / `${request-id}`|`requestid.New()`| Request ID stored by the requestid middleware. |
139
+
|`${username}`|`basicauth.New()`| Authenticated username stored by the basicauth middleware. |
140
+
|`${api-key}`|`keyauth.New()`| Redacted API key stored by the keyauth middleware. |
141
+
|`${csrf-token}`|`csrf.New()`| Redacted marker when the csrf middleware stores a token. |
142
+
|`${session-id}`|`session.New()` or `session.NewWithStore()`| Redacted session ID stored by the session middleware. |
143
+
144
+
:::note
145
+
Auto-registered tags are access-log tags for `middleware/logger`. The same names are also registered for application logs in the `log` package via `logger.RegisterContextTag` — see [api/log#context-tags](../api/log.md#context-tags) for details on `log.WithContext` enrichment.
146
+
:::
147
+
148
+
### Register Tags from Custom Middleware
149
+
150
+
Third-party middleware can expose logger tags with `logger.RegisterTag` or `logger.MustRegisterTag`. Use `sync.Once` so the tag is registered once even when the middleware is initialized multiple times.
To combine the logger middleware with loggers like Zerolog, Zap, or Logrus, use the `LoggerToWriter` helper to adapt them to an `io.Writer`.
@@ -166,7 +251,7 @@ Writing to `os.File` is goroutine-safe, but custom streams may require locking t
166
251
| Next |`func(fiber.Ctx) bool`| Next defines a function to skip this middleware when it returns true. |`nil`|
167
252
| Skip |`func(fiber.Ctx) bool`| Skip is a function to determine if logging is skipped or written to Stream. |`nil`|
168
253
| Done |`func(fiber.Ctx, []byte)`| Done is a function that is called after the log string for a request is written to Stream, and pass the log string as parameter. |`nil`|
169
-
| CustomTags |`map[string]LogFunc`|tagFunctions defines the custom tag action. |`map[string]LogFunc`|
254
+
| CustomTags |`map[string]LogFunc`|Defines custom tag actions for this logger instance. These tags override built-in and globally registered tags with the same name.|`nil`|
170
255
|`Format`|`string`| Defines the logging tags. See more in [Predefined Formats](#predefined-formats), or create your own using [Tags](#constants). |`[${time}] ${ip} ${status} - ${latency} ${method} ${path} ${error}\n` (same as `DefaultFormat`) |
171
256
| TimeFormat |`string`| TimeFormat defines the time format for log timestamps. |`15:04:05`|
172
257
| TimeZone |`string`| TimeZone can be specified, such as "UTC" and "America/New_York" and "Asia/Chongqing", etc |`"Local"`|
@@ -203,7 +288,7 @@ Logger provides predefined formats that you can use by name or directly by speci
|`CommonFormat`|`"${ip} - - [${time}] "${method} ${url} ${protocol}" ${status} ${bytesSent}\n"`| Common Log Format (CLF) used in web server logs. |
205
290
|`CombinedFormat`|`"${ip} - - [${time}] "${method} ${url} ${protocol}" ${status} ${bytesSent} "${referer}" "${ua}"\n"`| CLF format plus the `referer` and `user agent` fields. |
206
-
|`JSONFormat`|`"{time: ${time}, ip: ${ip}, method: ${method}, url: ${url}, status: ${status},bytesSent: ${bytesSent}}\n"`| JSON format for structured logging. |
291
+
|`JSONFormat`|`"{\"time\":\"${time}\",\"ip\":\"${ip}\",\"method\":\"${method}\",\"url\":\"${url}\",\"status\":${status},\"bytesSent\":${bytesSent}}\n"`| JSON format for structured logging. |
207
292
|`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"`| Elastic Common Schema (ECS) format for structured logging. |
0 commit comments