Skip to content

Commit

Permalink
Add X-Request-ID header value to error log
Browse files Browse the repository at this point in the history
Add `X-Request-ID` header value to log message when present

Closes issue #15
  • Loading branch information
bloomonkey committed Nov 8, 2023
1 parent 0c92310 commit e8489f5
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 4 deletions.
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]
### Added
- Emit error message when an exception is handled by the built application
- Emit error message when an exception is handled by the built application. Add `X-Request-ID` header value to log message when present

## [0.6.2] - 2023-08-23
### Fixed
Expand Down
6 changes: 4 additions & 2 deletions fastapi_mlflow/applications.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,12 @@ def build_app(pyfunc_model: PyFuncModel) -> FastAPI:

@app.exception_handler(DictSerialisableException)
def handle_serialisable_exception(
_: Request, exc: DictSerialisableException
req: Request, exc: DictSerialisableException
) -> ORJSONResponse:
nonlocal logger
logger.exception(exc.message)
req_id = req.headers.get("x-request-id")
extra = {"x-request-id": req_id} if req_id is not None else {}
logger.exception(exc.message, extra=extra)
return ORJSONResponse(
status_code=500,
content=exc.to_dict(),
Expand Down
33 changes: 32 additions & 1 deletion tests/test_application.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,4 +105,35 @@ def test_built_application_logs_exceptions(
assert len(caplog.records) >= 1
log_record = caplog.records[-1]
assert log_record.name == "fastapi_mlflow.applications"
assert log_record.message == python_model_value_error.ERROR_MESSAGE
assert log_record.message == python_model_value_error.ERROR_MESSAGE


@pytest.mark.parametrize(
"req_id_header_name",
[
"x-request-id",
"X-Request-Id",
"X-Request-ID",
"X-REQUEST-ID",
],
)
def test_built_application_logs_exceptions_including_request_id_header_when_sent(
model_input: pd.DataFrame,
pyfunc_model_value_error: PyFuncModel,
python_model_value_error: PythonModel,
caplog: pytest.LogCaptureFixture,
req_id_header_name: str
):
app = build_app(pyfunc_model_value_error)
client = TestClient(app, raise_server_exceptions=False)
df_str = model_input.to_json(orient="records")
request_data = f'{{"data": {df_str}}}'
request_id = "abcdef"

_ = client.post(
"/predictions", content=request_data, headers={req_id_header_name: request_id}
)

log_record = caplog.records[-1]
assert hasattr(log_record, "x-request-id")
assert getattr(log_record, "x-request-id") == request_id

0 comments on commit e8489f5

Please sign in to comment.