Skip to content

Commit

Permalink
Make logging examples more robust.
Browse files Browse the repository at this point in the history
Prevent them from crashing when the opening handshake didn't complete
successfully.

Also migrate them to the new asyncio API.

Fix #1428.
  • Loading branch information
aaugustin committed Aug 22, 2024
1 parent d3dcfd1 commit 4920a58
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 7 deletions.
15 changes: 9 additions & 6 deletions docs/topics/logging.rst
Original file line number Diff line number Diff line change
Expand Up @@ -124,9 +124,11 @@ Here's how to include them in logs, assuming they're in the
def process(self, msg, kwargs):
try:
websocket = kwargs["extra"]["websocket"]
except KeyError:
except KeyError: # log entry not coming from a connection
return msg, kwargs
if websocket.request is None: # opening handshake not complete
return msg, kwargs
xff = websocket.request_headers.get("X-Forwarded-For")
xff = headers.get("X-Forwarded-For")
return f"{websocket.id} {xff} {msg}", kwargs

async with serve(
Expand Down Expand Up @@ -165,10 +167,11 @@ a :class:`~logging.LoggerAdapter`::
websocket = kwargs["extra"]["websocket"]
except KeyError:
return msg, kwargs
kwargs["extra"]["event_data"] = {
"connection_id": str(websocket.id),
"remote_addr": websocket.request_headers.get("X-Forwarded-For"),
}
event_data = {"connection_id": str(websocket.id)}
if websocket.request is not None: # opening handshake complete
headers = websocket.request.headers
event_data["remote_addr"] = headers.get("X-Forwarded-For")
kwargs["extra"]["event_data"] = event_data
return msg, kwargs

async with serve(
Expand Down
2 changes: 1 addition & 1 deletion src/websockets/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ class ServerProtocol(Protocol):
max_size: Maximum size of incoming messages in bytes;
:obj:`None` disables the limit.
logger: Logger for this connection;
defaults to ``logging.getLogger("websockets.client")``;
defaults to ``logging.getLogger("websockets.server")``;
see the :doc:`logging guide <../../topics/logging>` for details.
"""
Expand Down

0 comments on commit 4920a58

Please sign in to comment.