Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

(fastapi) Log request ID when set in headers #100

Merged
merged 5 commits into from
Feb 28, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion src/dockerflow/fastapi/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,11 +66,18 @@ def _format(self, scope: HTTPScope, info) -> Dict[str, Any]:
info["request_headers"][header_key] = header_val

request_duration_ms = (info["end_time"] - info["start_time"]) * 1000.0
return {
fields = {
"agent": info["request_headers"].get("user-agent", ""),
"path": scope["path"],
"method": scope["method"],
"code": info["response"]["status"],
"lang": info["request_headers"].get("accept-language"),
"t": int(request_duration_ms),
}
try:
# Log the request ID if it's set by the reverse proxy
# or by a library like `asgi-correlation-id`.
fields["rid"] = info["request_headers"]["x-request-id"]
except KeyError:
pass
Copy link
Contributor

@grahamalama grahamalama Feb 26, 2024

Choose a reason for hiding this comment

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

Should we use setdefault, then build fields after that?

info["request_headers"].setdefault("x-request-id", uuid4())

fields = {
  ...,
  "rid": info["request_headers"]["x-request-id"]
}

return fields
12 changes: 12 additions & 0 deletions tests/fastapi/test_fastapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,18 @@ def test_mozlog(client, caplog):
assert isinstance(record.t, int)


def test_mozlog_request_id(client, caplog):
client.get(
"/__lbheartbeat__",
headers={
"X-Request-ID": "tracked-value",
},
)
record = caplog.records[0]

assert record.rid == "tracked-value"


def test_mozlog_failure(client, mocker, caplog):
mocker.patch(
"dockerflow.fastapi.views.get_version", side_effect=ValueError("crash")
Expand Down