Debian Codegraph @

docs/topics/logging.rst

raw
1 Logging
2 =======
3
4 .. currentmodule:: websockets
5
6 Logs contents
7 -------------
8
9 When you run a WebSocket client, your code calls coroutines provided by
10 websockets.
11
12 If an error occurs, websockets tells you by raising an exception. For example,
13 it raises a :exc:`~exceptions.ConnectionClosed` exception if the other side
14 closes the connection.
15
16 When you run a WebSocket server, websockets accepts connections, performs the
17 opening handshake, runs the connection handler coroutine that you provided,
18 and performs the closing handshake.
19
20 Given this `inversion of control`_, if an error happens in the opening
21 handshake or if the connection handler crashes, there is no way to raise an
22 exception that you can handle.
23
24 .. _inversion of control: https://en.wikipedia.org/wiki/Inversion_of_control
25
26 Logs tell you about these errors.
27
28 Besides errors, you may want to record the activity of the server.
29
30 In a request/response protocol such as HTTP, there's an obvious way to record
31 activity: log one event per request/response. Unfortunately, this solution
32 doesn't work well for a bidirectional protocol such as WebSocket.
33
34 Instead, when running as a server, websockets logs one event when a
35 `connection is established`_ and another event when a `connection is
36 closed`_.
37
38 .. _connection is established: https://datatracker.ietf.org/doc/html/rfc6455.html#section-4
39 .. _connection is closed: https://datatracker.ietf.org/doc/html/rfc6455.html#section-7.1.4
40
41 By default, websockets doesn't log an event for every message. That would be
42 excessive for many applications exchanging small messages at a fast rate. If
43 you need this level of detail, you could add logging in your own code.
44
45 Finally, you can enable debug logs to get details about everything websockets
46 is doing. This can be useful when developing clients as well as servers.
47
48 See :ref:`log levels <log-levels>` below for a list of events logged by
49 websockets logs at each log level.
50
51 Configure logging
52 -----------------
53
54 websockets relies on the :mod:`logging` module from the standard library in
55 order to maximize compatibility and integrate nicely with other libraries::
56
57 import logging
58
59 websockets logs to the ``"websockets.client"`` and ``"websockets.server"``
60 loggers.
61
62 websockets doesn't provide a default logging configuration because
63 requirements vary a lot depending on the environment.
64
65 Here's a basic configuration for a server in production::
66
67 logging.basicConfig(
68 format="%(asctime)s %(message)s",
69 level=logging.INFO,
70 )
71
72 Here's how to enable debug logs for development::
73
74 logging.basicConfig(
75 format="%(asctime)s %(message)s",
76 level=logging.DEBUG,
77 )
78
79 By default, websockets elides the content of messages to improve readability.
80 If you want to see more, you can increase the :envvar:`WEBSOCKETS_MAX_LOG_SIZE`
81 environment variable. The default value is 75.
82
83 Furthermore, websockets adds a ``websocket`` attribute to log records, so you
84 can include additional information about the current connection in logs.
85
86 You could attempt to add information with a formatter::
87
88 # this doesn't work!
89 logging.basicConfig(
90 format="{asctime} {websocket.id} {websocket.remote_address[0]} {message}",
91 level=logging.INFO,
92 style="{",
93 )
94
95 However, this technique runs into two problems:
96
97 * The formatter applies to all records. It will crash if it receives a record
98 without a ``websocket`` attribute. For example, this happens when logging
99 that the server starts because there is no current connection.
100
101 * Even with :meth:`str.format` style, you're restricted to attribute and index
102 lookups, which isn't enough to implement some fairly simple requirements.
103
104 There's a better way. :func:`~asyncio.client.connect` and
105 :func:`~asyncio.server.serve` accept a ``logger`` argument to override the
106 default :class:`~logging.Logger`. You can set ``logger`` to a
107 :class:`~logging.LoggerAdapter` that enriches logs.
108
109 For example, if the server is behind a reverse
110 proxy, :attr:`~legacy.protocol.WebSocketCommonProtocol.remote_address` gives
111 the IP address of the proxy, which isn't useful. IP addresses of clients are
112 provided in an HTTP header set by the proxy.
113
114 Here's how to include them in logs, assuming they're in the
115 ``X-Forwarded-For`` header::
116
117 logging.basicConfig(
118 format="%(asctime)s %(message)s",
119 level=logging.INFO,
120 )
121
122 class LoggerAdapter(logging.LoggerAdapter):
123 """Add connection ID and client IP address to websockets logs."""
124 def process(self, msg, kwargs):
125 try:
126 websocket = kwargs["extra"]["websocket"]
127 except KeyError: # log entry not coming from a connection
128 return msg, kwargs
129 if websocket.request is None: # opening handshake not complete
130 return msg, kwargs
131 xff = headers.get("X-Forwarded-For")
132 return f"{websocket.id} {xff} {msg}", kwargs
133
134 async with serve(
135 ...,
136 logger=LoggerAdapter(logging.getLogger("websockets.server")),
137 ):
138 ...
139
140 Logging to JSON
141 ---------------
142
143 Even though :mod:`logging` predates structured logging, it's still possible to
144 output logs as JSON with a bit of effort.
145
146 First, we need a :class:`~logging.Formatter` that renders JSON:
147
148 .. literalinclude:: ../../experiments/json_log_formatter.py
149
150 Then, we configure logging to apply this formatter::
151
152 handler = logging.StreamHandler()
153 handler.setFormatter(formatter)
154
155 logger = logging.getLogger()
156 logger.addHandler(handler)
157 logger.setLevel(logging.INFO)
158
159 Finally, we populate the ``event_data`` custom attribute in log records with
160 a :class:`~logging.LoggerAdapter`::
161
162 class LoggerAdapter(logging.LoggerAdapter):
163 """Add connection ID and client IP address to websockets logs."""
164 def process(self, msg, kwargs):
165 try:
166 websocket = kwargs["extra"]["websocket"]
167 except KeyError:
168 return msg, kwargs
169 event_data = {"connection_id": str(websocket.id)}
170 if websocket.request is not None: # opening handshake complete
171 headers = websocket.request.headers
172 event_data["remote_addr"] = headers.get("X-Forwarded-For")
173 kwargs["extra"]["event_data"] = event_data
174 return msg, kwargs
175
176 async with serve(
177 ...,
178 logger=LoggerAdapter(logging.getLogger("websockets.server")),
179 ):
180 ...
181
182 Disable logging
183 ---------------
184
185 If your application doesn't configure :mod:`logging`, Python outputs messages
186 of severity ``WARNING`` and higher to :data:`~sys.stderr`. As a consequence,
187 you will see a message and a stack trace if a connection handler coroutine
188 crashes or if you hit a bug in websockets.
189
190 If you want to disable this behavior for websockets, you can add
191 a :class:`~logging.NullHandler`::
192
193 logging.getLogger("websockets").addHandler(logging.NullHandler())
194
195 Additionally, if your application configures :mod:`logging`, you must disable
196 propagation to the root logger, or else its handlers could output logs::
197
198 logging.getLogger("websockets").propagate = False
199
200 Alternatively, you could set the log level to ``CRITICAL`` for the
201 ``"websockets"`` logger, as the highest level currently used is ``ERROR``::
202
203 logging.getLogger("websockets").setLevel(logging.CRITICAL)
204
205 Or you could configure a filter to drop all messages::
206
207 logging.getLogger("websockets").addFilter(lambda record: None)
208
209 .. _log-levels:
210
211 Log levels
212 ----------
213
214 Here's what websockets logs at each level.
215
216 ``ERROR``
217 .........
218
219 * Exceptions raised by your code in servers
220 * connection handler coroutines
221 * ``select_subprotocol`` callbacks
222 * ``process_request`` and ``process_response`` callbacks
223 * Exceptions resulting from bugs in websockets
224
225 ``WARNING``
226 ...........
227
228 * Failures in :func:`~asyncio.server.broadcast`
229
230 ``INFO``
231 ........
232
233 * Server starting and stopping
234 * Server establishing and closing connections
235 * Client reconnecting automatically
236
237 ``DEBUG``
238 .........
239
240 * Changes to the state of connections
241 * Handshake requests and responses
242 * All frames sent and received
243 * Steps to close a connection
244 * Keepalive pings and pongs
245 * Errors handled transparently
246
247 Debug messages have cute prefixes that make logs easier to scan:
248
249 * ``>`` - send something
250 * ``<`` - receive something
251 * ``=`` - set connection state
252 * ``x`` - shut down connection
253 * ``%`` - manage pings and pongs
254 * ``-`` - timeout
255 * ``!`` - error, with a traceback