Skip to content

Commit

Permalink
Add IP address to flask request logs (#2180)
Browse files Browse the repository at this point in the history
* Add IP address to flask request logs
* Handle case of no x-forwarded-for
  • Loading branch information
jonathangreen authored Nov 20, 2024
1 parent c2b355b commit b1d8cb2
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
10 changes: 10 additions & 0 deletions src/palace/manager/service/logging/log.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,16 @@ def ensure_str(s: Any) -> Any:
if user_agent := flask_request.headers.get("User-Agent"):
data["request"]["user_agent"] = user_agent

forwarded_for_list = []
if forwarded_for := flask_request.headers.get("X-Forwarded-For"):
forwarded_for_list.extend(
[ip.strip() for ip in forwarded_for.split(",")]
)
if remote_addr := flask_request.remote_addr:
forwarded_for_list.append(remote_addr)
if forwarded_for_list:
data["request"]["forwarded_for"] = forwarded_for_list

# If we are running in uwsgi context, we include the worker id in the log
if uwsgi:
data["uwsgi"] = {"worker": uwsgi.worker_id()}
Expand Down
13 changes: 11 additions & 2 deletions tests/manager/service/logging/test_log.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,10 +182,18 @@ def test_flask_request(
assert request["method"] == "GET"
assert "host" in request
assert "query" not in request
assert "user-agent" not in request
assert "user_agent" not in request
assert "forwarded_for" not in request

with flask_app_fixture.test_request_context(
"/test?query=string&foo=bar", method="POST", headers={"User-Agent": "UA"}
"/test?query=string&foo=bar",
method="POST",
headers=[
("User-Agent", "UA"),
("X-Forwarded-For", "xyz, abc"),
("X-Forwarded-For", "123"),
],
environ_base={"REMOTE_ADDR": "456"},
):
data = json.loads(formatter.format(record))
assert "request" in data
Expand All @@ -194,6 +202,7 @@ def test_flask_request(
assert request["method"] == "POST"
assert request["query"] == "query=string&foo=bar"
assert request["user_agent"] == "UA"
assert request["forwarded_for"] == ["xyz", "abc", "123", "456"]

# If flask is not installed, the request data is not included in the log.
with patch("palace.manager.service.logging.log.flask_request", None):
Expand Down

0 comments on commit b1d8cb2

Please sign in to comment.