Repository navigation
feat(logging): add request ID and JSON logs - #684
Conversation
Each request gets an identifier from a WSGI middleware, available from `foca.context.request_id()`, echoed in a header and, with the filter `context`, in log records with its operation, subject and client. The formatter `json` writes one object per line, and `log` takes `loggers` and `filters`. The default format stays. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Deep nesting, NaN and values that can't be printed end up as text, and never fail a record. Restore the identifier of an outer request. Say what the configuration doesn't reach in Celery workers. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Other fields of a record keep their types, and a body failing to close still forgets the identifier. Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # docs/migration-0.21.md
Reviewer's GuideThis PR adds end-to-end request correlation and JSON logging: a configurable WSGI middleware assigns safe IDs and preserves them through response handling, contextual filters enrich records for requests and Celery tasks, a resilient built-in JSON formatter and expanded logging configuration integrate with stdlib logging, and documentation/tests cover deployment, plugin, operation, and migration behavior. Sequence diagram for request ID propagation and contextual loggingsequenceDiagram
participant Client
participant Middleware as RequestIdMiddleware
participant App as WSGI App
participant Handler as Log Handler
participant Formatter as JsonFormatter
Client->>Middleware: HTTP request with X-Request-ID
Middleware->>Middleware: _get_id(environ)
Middleware->>App: __call__(environ, _start_response)
App->>Middleware: _start_response(status, headers)
Middleware->>Client: Response with request ID header
App->>Handler: LogRecord
Handler->>Handler: ContextFilter.filter(record)
Handler->>Formatter: format(record)
Formatter-->>Handler: JSON log line
Middleware-->>Middleware: _ResponseBody.close()
Middleware->>Middleware: _clear()
File-Level Changes
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## dev #684 +/- ##
==========================================
Coverage 100.00% 100.00%
==========================================
Files 60 61 +1
Lines 7908 8071 +163
==========================================
+ Hits 7908 8071 +163
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Python's logging.config ignores the defaults of formatters before Python 3.12 (documented now), and how deep a nested value can be written depends on the version. Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
Hey - I've found 13 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="foca/factories/connexion_app.py" line_range="195-198" />
<code_context>
conf.host,
)
+ app.app.wsgi_app = RequestIdMiddleware(
+ app.app.wsgi_app,
+ header=conf.request_id.header,
+ trust_incoming=conf.request_id.trust_incoming,
+ )
+
</code_context>
<issue_to_address>
**Requests lack request ID context**
When an app is created with `create_connexion_app()` and no config, `create_connexion_app` skips `__add_config_to_connexion_app`, so `RequestIdMiddleware` is never installed and requests receive neither the request-ID response header nor a request context ID.
Install `RequestIdMiddleware` on the no-config factory path as well.
</issue_to_address>
### Comment 2
<location path="foca/models/config.py" line_range="207" />
<code_context>
+ True
+ """
+
+ header: str = Field(default="X-Request-ID", pattern=r"^[A-Za-z0-9-]+$")
+ trust_incoming: bool = True
+
</code_context>
<issue_to_address>
**Response headers are corrupted**
When `server.request_id.header` is set to a standard header such as `Content-Length`, `Content-Type` or `Set-Cookie`, `RequestIdConfig` accepts the header, and `RequestIdMiddleware` reads or replaces it with the request ID; WSGI exposes `Content-Length` as `CONTENT_LENGTH`, so the request ID can also be missed on input. Clients receive invalid response framing or content type, or lose cookies.
Reject standard headers that WSGI treats specially or that the middleware would overwrite on the response.
Also at `foca/context.py:106`, `foca/context.py:151-152`.
</issue_to_address>
### Comment 3
<location path="foca/models/config.py" line_range="2789" />
<code_context>
+ handler.filters = ["context"]
+ users: list[tuple[str, LogHandlerConfig | LogLoggerConfig]] = [
+ *handlers.items(),
+ *self.loggers.items(),
+ ]
+ unknown = sorted(
</code_context>
<issue_to_address>
**Invalid root handlers pass validation**
When `log.root.handlers` names a handler absent from `log.handlers`, `LogConfig._add_builtins_and_check_names` checks configured logger references but omits `root.handlers`, so `dictConfig` rejects the configuration and `ConfigParser` falls back to default logging instead of applying the requested setup.
Include `root.handlers` in the handler-reference validation.
Also at `foca/models/config.py:2790`, `foca/models/config.py:2801-2803`.
</issue_to_address>
### Comment 4
<location path="foca/context.py" line_range="166" />
<code_context>
+ body = self.app(environ, _start_response)
+ file_wrapper = environ.get("wsgi.file_wrapper")
+ if isinstance(file_wrapper, type) and isinstance(body, file_wrapper):
+ _clear()
+ return body
+ return _ResponseBody(body, _clear)
</code_context>
<issue_to_address>
**File-response logs lose request context**
When a WSGI app returns a file-wrapper response and code consults request context or logs while the server sends its body, `RequestIdMiddleware` calls `_clear()` before the server consumes the wrapper, so `request_id()` and stream-time log records see no request ID or an enclosing request's ID, and the file response's logs lose correlation.
Keep the request context active until the file wrapper is consumed or closed, then restore the previous context.
</issue_to_address>
### Comment 5
<location path="foca/context.py" line_range="30" />
<code_context>
+ if value is not None:
+ return value
+ if current_task:
+ return str(current_task.request.id or "")
+ return ""
+
</code_context>
<issue_to_address>
**Control characters forge log lines**
When a Celery task ID or configured operation ID contains a line-breaking control character, `request_id()` returns task IDs unchanged and `_get_context()` stores operation IDs unchanged, so text log records include unescaped control characters and can be split into forged lines.
Escape or remove line-breaking control characters from task and operation IDs before adding them to log records.
Also at `foca/utils/logging.py:54`, `foca/utils/logging.py:67`.
</issue_to_address>
### Comment 6
<location path="foca/models/config.py" line_range="209" />
<code_context>
handlers: [console]
```
+Besides what is shown here, `formatters` can have `datefmt` and `defaults` (values of
+fields that a record may lack; Python's logging ignores them before Python 3.12), and
</code_context>
<issue_to_address>
**Clients can spoof request correlation**
When an untrusted client can reach the application and send a syntactically valid request-ID header, `RequestIdMiddleware` accepts the client’s chosen identifier and echoes it in the response, so unrelated attacker-controlled requests can be grouped under an identifier used in log searches, polluting request correlation during investigations.
Default `trust_incoming` to false, requiring deployments that rely on a trusted proxy to enable it explicitly.
Also at `foca/context.py:94`, `foca/context.py:118`.
</issue_to_address>
### Comment 7
<location path="foca/context.py" line_range="165-166" />
<code_context>
+ try:
+ body = self.app(environ, _start_response)
+ file_wrapper = environ.get("wsgi.file_wrapper")
+ if isinstance(file_wrapper, type) and isinstance(body, file_wrapper):
+ _clear()
+ return body
+ return _ResponseBody(body, _clear)
</code_context>
<issue_to_address>
**File-transfer optimization is lost**
When a WSGI server provides `wsgi.file_wrapper` as a callable factory rather than a class, `RequestIdMiddleware` only recognizes class-valued wrappers, so it wraps the factory's returned body in `_ResponseBody`; the server no longer recognizes its optimized wrapper and large downloads fall back to ordinary iteration.
Preserve callable file-wrapper responses without wrapping their returned bodies in `_ResponseBody`.
</issue_to_address>
### Comment 8
<location path="foca/context.py" line_range="161" />
<code_context>
+ """Forget the identifier, for the request that an app may be called in."""
+ _request_id.set(previous)
+
+ _request_id.set(value)
+ try:
+ body = self.app(environ, _start_response)
</code_context>
<issue_to_address>
**Overlapping streams share request ID**
When a caller starts request B in the same execution context before closing request A's streaming response, request B overwrites the context while request A's response remains open, so A's stream can log B's ID. If A then closes, its saved `previous` value can also overwrite B's active ID, leaving subsequent logs with stale context.
Isolate the request ID for each response's body iteration instead of leaving one mutable context value active across overlapping response lifetimes.
</issue_to_address>
### Comment 9
<location path="foca/utils/logging.py" line_range="152" />
<code_context>
+ extra = {
+ key: value
+ for key, value in vars(record).items()
+ if key not in _RECORD_ATTRIBUTES and not key.startswith("_")
+ }
+ # Records of handlers without `ContextFilter`
</code_context>
<issue_to_address>
**Non-string extra keys break logging**
When a record is given a non-string key in `extra`, `key.startswith` raises `AttributeError` while `JsonFormatter` collects extra attributes, before the serialization fallback runs, so the log record is not emitted.
Check that each key is a string before calling `startswith`.
</issue_to_address>
### Comment 10
<location path="foca/utils/logging.py" line_range="100-103" />
<code_context>
+ The value if it can be written as JSON, otherwise its text.
+ """
+ try:
+ json.dumps(value, default=_to_text, allow_nan=False)
+ except Exception:
+ return _to_text(value)
+ return value
+
+
</code_context>
<issue_to_address>
**Some mixed records lose their log line**
When a record contains both a value unsupported by JSON, such as `object()`, and a value that triggers the fallback, such as NaN, `_to_json_value` accepts an unsupported object because `json.dumps(..., default=_to_text)` succeeds, then returns the original object. When another field such as NaN triggers the fallback, the final `json.dumps` has no `default` and raises `TypeError`, so the record is not emitted.
Convert unsupported values to text in the fallback path even when the probe succeeds only because of `default=_to_text`.
</issue_to_address>
### Comment 11
<location path="foca/utils/logging.py" line_range="157-158" />
<code_context>
+ # Records of handlers without `ContextFilter`
+ context = (
+ {name: getattr(record, name) for name in _CONTEXT_FIELDS}
+ if all(hasattr(record, name) for name in _CONTEXT_FIELDS)
+ else _get_context()
+ )
+ data = {
</code_context>
<issue_to_address>
**Extra fields can spoof JSON context**
When a record supplies all four context names through `extra` and its handler has no `ContextFilter`, `JsonFormatter` treats all four context attributes supplied through `extra` as trusted context when no `ContextFilter` ran, so the JSON record reports caller-supplied IDs and identity fields instead of the current context.
Ensure reserved context fields in JSON output come from trusted context rather than values supplied through `extra`.
</issue_to_address>
### Comment 12
<location path="tests/utils/test_logging_context.py" line_range="428" />
<code_context>
+ try:
+ dictConfig(conf.model_dump(by_alias=True, exclude_none=True))
+ logger.handlers[0].setStream(stream) # type: ignore[attr-defined]
+ logger.info("ignored")
+ logger.warning("shown")
+ assert stream.getvalue() == "|WARNING|shown\n"
</code_context>
<issue_to_address>
**Configured filter is not exercised**
When the test runs with its configured logger level of 30, `logger.info("ignored")` at line 428 is suppressed by the level of 30 before the filter runs, while the warning is allowed by the configured filter. The exact output asserted at line 430 therefore passes even if `only_a` is never applied.
Use a warning-level record that the filter should reject, and assert it is absent while an allowed record is present.
</issue_to_address>
### Comment 13
<location path="tests/plugins/test_plugin_adapter.py" line_range="34" />
<code_context>
- """Request IDs come from safe client headers or are generated."""
+ """Requests have the identifier of the middleware, else a random one."""
app = Flask(__name__)
assert len(adapter.request_id()) == 32
- with app.test_request_context(headers={"X-Request-ID": "abc-1"}):
- assert adapter.request_id() == "abc-1"
</code_context>
<issue_to_address>
**Fallback ID is not checked**
When `adapter.request_id()` has no middleware-provided identifier, `assert len(adapter.request_id()) == 32` at line 34 accepts any 32-character value, so a fixed constant can replace the UUID fallback and this assertion still passes.
Assert that the fallback matches the expected UUID format and differs across independent calls.
</issue_to_address>Linked issues
#620 feat(logging): add request ID and JSON logs · 9 of 10 met · 1 to check by hand
| # | Requirement | Status | Notes |
|---|---|---|---|
| 1 | Provide a configurable WSGI request ID, echoing a valid trusted incoming value or generating one otherwise. | ✅ Met | RequestIdMiddleware validates incoming IDs, supports a configurable header and trust setting, and adds the ID to responses; tests cover valid, invalid, missing, untrusted, and custom-header cases. |
| 2 | Expose the request ID through foca.context.request_id() and use it in the plugin adapter. |
✅ Met | The context accessor reads the ContextVar (or the Celery task ID), and the adapter delegates to it. |
| 3 | Add request_id, operation_id, subject, and client to log records; outside requests, fields are empty and logging does not fail. |
✅ Met | ContextFilter adds all four fields; tests cover request context, empty fields outside requests, and failures while retrieving context. |
| 4 | Use the Celery task ID for request_id in task logs. |
👀 Check by hand (runtime) | The code reads current_task.request.id and tests this with a mock, but the PR reports that no real Celery worker was run; verify the task ID appears in logs from an actual worker. |
| 5 | Provide a stdlib JSON formatter that writes one valid JSON object per line with timestamp, level, logger, message, context, exceptions, and extra fields. | ✅ Met | JsonFormatter includes these fields and tests cover exceptions, extra data, unusual values, and valid single-line JSON. |
| 6 | Support logging filters and named loggers, formatter datefmt and defaults, and handler filters; validate referenced names and pass the configuration to dictConfig. |
✅ Met | The config models add these options, validate filter and handler references, and the parser passes their model dump to dictConfig. |
| 7 | Keep the default formatter and existing defaults unchanged. | ✅ Met | The standard formatter remains the default, while the context filter is added to handlers without explicit filters; the migration docs note that default log lines stay the same. |
| 8 | Include the request ID in Gunicorn's access log format. | ✅ Met | access_log_format includes the default X-Request-ID response header, and access logging remains disabled by default. |
| 9 | Document request IDs, contextual logging, JSON logs, and the expanded logging configuration. | ✅ Met | The configuration, deployment, plugin, and migration docs describe the new behavior and its migration impact. |
| 10 | Meet the stated 100% coverage, mypy, ruff, and strict docs-build checks. | ✅ Met | The PR description reports these checks passed, and the diff adds tests for the new middleware, logging, and configuration behavior. |
Sourcery assessment
Needs a human reviewer. 13 findings to address first, and when JSON logging is enabled, each record now includes the validated token subject and client, which may identify users and persist in log storage. Reverting stops future records from including them, but does not remove entries already collected or accessed.
Blocking findings: foca/factories/connexion_app.py:198, foca/models/config.py:207, foca/models/config.py:2789, foca/context.py:166, foca/context.py:30, and 8 more
# Conflicts: # tests/conftest.py
From review: refuse standard headers as header of request IDs, check the handlers of the root logger, escape task and operation identifiers, and keep JSON records with keys that aren't strings or mixed odd values. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
Closes #620.
foca.context.request_id(), in aContextVar, andRequestIdMiddlewarearoundapp.wsgi_app: header fromserver.request_id.header(defaultX-Request-ID); an incoming value is taken if it matches^[A-Za-z0-9._:-]{1,128}$andserver.request_id.trust_incomingis on (default), otherwiseuuid4().hex; echoed in the response. The plugin adapter'srequest_id()uses it.foca.utils.logging.ContextFilter:request_id,operation_id,subject,clienton records; empty outside requests, with the task ID in Celery tasks.foca.utils.logging.JsonFormatter, built-in formatterjson: one JSON object per line, stdlib only.log.filters,log.loggers,datefmtanddefaultsof formatters,filtersof handlers; names are validated. The default format staysstandard; handlers withoutfiltersget the built-incontext.foca.gunicorn_config.access_log_formatwith the request ID (access log stays off by default).docs/configuration/log.md,docs/configuration/server.md,docs/deployment.md,docs/plugins.md,docs/migration-0.21.md.New response header on all routes, also for unmatched ones; noted in the migration guide.
Verification
ruff,mypy foca tests, strict docs build, fullpytestwith MongoDB, 100% coverage.send_fileresponses and a 404: the right ID in the header and access log, and correct while streaming.current_taskand from reading Celery's source and callingCelery.log.setup().Declined review findings
worker_hijack_root_logger: Falseandlogging.getLogger(__name__)in tasks.operation_idforx-openapi-router-controller: falls back on the name of the endpoint, as documented. FOCA's specs use dotted IDs.Nonein filter arguments is dropped:exclude_noneis needed for the optional fields; such a factory can use another value.except Exceptionin the filter: a log filter must not fail logging, whatever the app has as config; there's no narrower type to catch.access_log_formatassumes the default header: Gunicorn's config has no access to the app's; documented indocs/configuration/server.md.Open questions
None.
🤖 Generated with Claude Code
Summary by Sourcery
Add request correlation and structured logging support throughout FOCA.
New Features:
Bug Fixes:
Documentation:
Tests: