Skip to content

feat(logging): add request ID and JSON logs - #684

Merged
uniqueg merged 8 commits into
devfrom
feat/620-request-id-logs
Nov 4, 2026
Merged

uniqueg merged 8 commits into
devfrom
feat/620-request-id-logs

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 4, 2026 •

Copy link
Copy Markdown
Member

Summary

Closes #620.

  • foca.context.request_id(), in a ContextVar, and RequestIdMiddleware around app.wsgi_app: header from server.request_id.header (default X-Request-ID); an incoming value is taken if it matches ^[A-Za-z0-9._:-]{1,128}$ and server.request_id.trust_incoming is on (default), otherwise uuid4().hex; echoed in the response. The plugin adapter's request_id() uses it.
  • foca.utils.logging.ContextFilter: request_id, operation_id, subject, client on records; empty outside requests, with the task ID in Celery tasks.
  • foca.utils.logging.JsonFormatter, built-in formatter json: one JSON object per line, stdlib only.
  • log.filters, log.loggers, datefmt and defaults of formatters, filters of handlers; names are validated. The default format stays standard; handlers without filters get the built-in context.
  • foca.gunicorn_config.access_log_format with the request ID (access log stays off by default).
  • Docs: 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, full pytest with MongoDB, 100% coverage.
  • The reviewer ran real Gunicorn (gthread, one thread) for plain, streamed and send_file responses and a 404: the right ID in the header and access log, and correct while streaming.
  • No real Celery worker was run. Task ID and worker docs come from tests with a mock of current_task and from reading Celery's source and calling Celery.log.setup().

Declined review findings

  • Celery task loggers keep Celery's handler: the issue only asks for the task ID; changing how workers log is a behaviour change that fits feat: worker jobs, index errors, removed-key hints #622, if wanted. Documented: worker_hijack_root_logger: False and logging.getLogger(__name__) in tasks.
  • operation_id for x-openapi-router-controller: falls back on the name of the endpoint, as documented. FOCA's specs use dotted IDs.
  • Explicit None in filter arguments is dropped: exclude_none is needed for the optional fields; such a factory can use another value.
  • except Exception in the filter: a log filter must not fail logging, whatever the app has as config; there's no narrower type to catch.
  • access_log_format assumes the default header: Gunicorn's config has no access to the app's; documented in docs/configuration/server.md.
  • The validator adds to the model: intended, so that dumps are what's applied.

Open questions

None.

🤖 Generated with Claude Code

Summary by Sourcery

Add request correlation and structured logging support throughout FOCA.

New Features:

  • Add configurable request IDs across WSGI requests, including response propagation, application context access, plugin integration, and Gunicorn access logs.
  • Add contextual logging fields for request and Celery task identifiers, operation IDs, subjects, and clients.
  • Add a built-in JSON log formatter and expanded logging configuration for custom filters, loggers, formatter defaults, and handler filters.

Bug Fixes:

  • Ensure request identifiers remain available during streamed responses and are cleared after request completion or failure.
  • Validate request ID headers and logging references to prevent unsafe values and invalid configuration.

Documentation:

  • Document request ID configuration, contextual and JSON logging, deployment behavior, plugin integration, and migration considerations.

Tests:

  • Add comprehensive coverage for request ID middleware, request context, logging context, JSON formatting, configuration validation, and Gunicorn integration.

uniqueg and others added 4 commits November 4, 2026 08:19
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]>
@uniqueg uniqueg added this to the v0.21.0 milestone Nov 4, 2026
@sourcery-ai

sourcery-ai Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

This 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 logging

sequenceDiagram
    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()
Loading

File-Level Changes

Change Details Files
Add configurable request correlation IDs across WSGI requests and application integrations.
  • Introduce a ContextVar-backed request ID API with validation, trust controls, UUID fallback, and Celery task fallback.
  • Wrap the Connexion/Flask WSGI app to assign and echo IDs, including unmatched, streamed, error, and file-wrapper responses.
  • Update the plugin adapter and Gunicorn access-log format to use the configured request ID header.
  • Add server configuration and migration documentation.
foca/context.py
foca/factories/connexion_app.py
foca/gunicorn_config.py
foca/models/config.py
foca/plugins/adapter.py
docs/configuration/server.md
docs/deployment.md
docs/plugins.md
docs/migration-0.21.md
tests/test_context.py
tests/test_gunicorn_config.py
tests/plugins/test_plugin_adapter.py
Add contextual and structured logging while preserving existing standard logging behavior.
  • Add a ContextFilter that supplies request/task ID, operation ID, subject, and client fields while safely handling missing FOCA context and escaping log values.
  • Add a stdlib-only JsonFormatter with timestamps, core context, exception/stack data, extra fields, and resilient serialization of non-JSON values.
  • Register built-in context filter and JSON formatter, automatically apply context to handlers unless explicitly configured otherwise, and support formatter datefmt/defaults.
  • Document JSON output, contextual fields, Celery behavior, privacy considerations, and logging configuration.
foca/utils/logging.py
foca/models/config.py
foca/config/config_parser.py
docs/configuration/log.md
tests/utils/test_logging_context.py
Expand logging configuration with named loggers and filters plus reference validation.
  • Support named logger/filter configuration, handler filters, formatter defaults, and custom filter factories.
  • Validate referenced handler and filter names while allowing applications to replace built-in context and JSON definitions.
  • Retain standard formatting as the default and pass configurations to dictConfig without unintended None values.
foca/models/config.py
foca/config/config_parser.py
docs/configuration/log.md
tests/utils/test_logging_context.py
Expose operation metadata for contextual request logs and public API reference documentation.
  • Track registered OpenAPI operation IDs and resolve the current request's operation, with endpoint-name fallback and empty values outside matched routes.
  • Expose the context module in generated reference documentation.
foca/utils/urls.py
docs/reference.md
tests/utils/test_logging_context.py

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@codecov

codecov Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (0c22684) to head (305bda0).

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     
Flag Coverage Δ
test_unit 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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]>
@uniqueg
uniqueg marked this pull request as ready for review November 4, 2026 08:01

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread foca/factories/connexion_app.py Resolved
Comment thread foca/models/config.py Resolved
Comment thread foca/models/config.py Resolved
Comment thread foca/context.py Resolved
Comment thread foca/context.py Resolved
Comment thread foca/utils/logging.py Resolved
Comment thread foca/utils/logging.py Resolved
Comment thread foca/utils/logging.py Resolved
Comment thread tests/utils/test_logging_context.py Resolved
Comment thread tests/plugins/test_plugin_adapter.py Resolved
uniqueg and others added 3 commits November 4, 2026 09:11
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]>
@uniqueg
uniqueg merged commit 874a155 into dev Nov 4, 2026
56 checks passed
@uniqueg
uniqueg deleted the feat/620-request-id-logs branch November 4, 2026 09:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(logging): add request ID and JSON logs

1 participant