Skip to content

Commit 191e91c

Browse files
committed
Changed format of debug logs, added Response.size, fix in send_chunk
1 parent 33d6b25 commit 191e91c

File tree

3 files changed

+42
-22
lines changed

3 files changed

+42
-22
lines changed

adafruit_httpserver/response.py

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,9 @@ def route_func(request):
9090
Common MIME types are defined in `adafruit_httpserver.mime_types`.
9191
"""
9292

93+
size: int = 0
94+
"""Size of the response in bytes."""
95+
9396
def __init__( # pylint: disable=too-many-arguments
9497
self,
9598
request: Request,
@@ -192,6 +195,9 @@ def send(
192195
self._send_bytes(self.request.connection, encoded_response_message_body)
193196
self._response_already_sent = True
194197

198+
if self.request.server.debug:
199+
_debug_response_sent(self)
200+
195201
@staticmethod
196202
def _check_file_path_is_valid(file_path: str) -> bool:
197203
"""
@@ -270,6 +276,9 @@ def send_file( # pylint: disable=too-many-arguments
270276
self._send_bytes(self.request.connection, bytes_read)
271277
self._response_already_sent = True
272278

279+
if self.request.server.debug:
280+
_debug_response_sent(self)
281+
273282
def send_chunk(self, chunk: str = "") -> None:
274283
"""
275284
Sends chunk of response.
@@ -279,6 +288,7 @@ def send_chunk(self, chunk: str = "") -> None:
279288
280289
:param str chunk: String data to be sent.
281290
"""
291+
self._check_if_not_already_sent()
282292
self._check_chunked(True)
283293

284294
if getattr(chunk, "encode", None):
@@ -299,14 +309,19 @@ def __exit__(self, exception_type, exception_value, exception_traceback):
299309

300310
if self.chunked:
301311
self.send_chunk("")
312+
self._response_already_sent = True
313+
314+
if self.chunked and self.request.server.debug:
315+
_debug_response_sent(self)
316+
302317
return True
303318

304-
@staticmethod
305319
def _send_bytes(
320+
self,
306321
conn: Union["SocketPool.Socket", "socket.socket"],
307322
buffer: Union[bytes, bytearray, memoryview],
308323
):
309-
bytes_sent = 0
324+
bytes_sent: int = 0
310325
bytes_to_send = len(buffer)
311326
view = memoryview(buffer)
312327
while bytes_sent < bytes_to_send:
@@ -318,3 +333,16 @@ def _send_bytes(
318333
if exc.errno == ECONNRESET:
319334
return
320335
raise
336+
self.size += bytes_sent
337+
338+
339+
def _debug_response_sent(response: "Response"):
340+
"""Prints a message when after a response is sent."""
341+
client_ip = response.request.client_address[0]
342+
method = response.request.method
343+
path = response.request.path
344+
req_size = len(response.request.raw_request)
345+
status = response.status
346+
res_size = response.size
347+
348+
print(f'{client_ip} -- "{method} {path}" {req_size} -- "{status}" {res_size}')

adafruit_httpserver/server.py

Lines changed: 1 addition & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -309,9 +309,6 @@ def poll(self):
309309
if (request := self._receive_request(conn, client_address)) is None:
310310
return
311311

312-
if self.debug:
313-
_debug_incoming_request(request)
314-
315312
# Find a handler for the route
316313
handler = self._routes.find_handler(
317314
_Route(request.path, request.method)
@@ -397,19 +394,10 @@ def _debug_started_server(server: "Server"):
397394

398395

399396
def _debug_stopped_server(server: "Server"): # pylint: disable=unused-argument
400-
"""Prints a message when the server stops."""
397+
"""Prints a message after the server stops."""
401398
print("Stopped development server")
402399

403400

404-
def _debug_incoming_request(request: "Request"):
405-
"""Prints a message when a request is received."""
406-
client_ip = request.client_address[0]
407-
method = request.method
408-
size = len(request.raw_request)
409-
410-
print(f"{client_ip} -- {method} {request.path} {size}")
411-
412-
413401
def _debug_exception_in_handler(error: Exception):
414402
"""Prints a message when an exception is raised in a handler."""
415403
print_exception(error)

docs/examples.rst

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -228,25 +228,29 @@ During development it is useful to see the logs from the server.
228228
You can enable debug mode by setting ``debug=True`` on ``Server`` instance or in constructor,
229229
it is disabled by default.
230230

231-
Debug mode prints messages on server startup, when a request is received and if exception
231+
Debug mode prints messages on server startup, after sending a response to a request and if exception
232232
occurs during handling of the request in ``.serve_forever()``.
233233

234234
This is how the logs might look like when debug mode is enabled::
235235

236236
Started development server on http://192.168.0.100:80
237-
192.168.0.101 -- GET / 194
238-
192.168.0.101 -- GET /example 194
239-
192.168.0.102 -- POST /api 241
237+
192.168.0.101 -- "GET /" 194 -- "200 OK" 154
238+
192.168.0.101 -- "GET /example" 134 -- "404 Not Found" 172
239+
192.168.0.102 -- "POST /api" 1241 -- "401 Unauthorized" 95
240240
Traceback (most recent call last):
241241
...
242242
File "code.py", line 55, in example_handler
243243
KeyError: non_existent_key
244-
192.168.0.103 -- GET /index.html 242
244+
192.168.0.103 -- "GET /index.html" 242 -- "200 OK" 154
245245
Stopped development server
246246

247+
This is the default format of the logs::
247248

248-
If you need more information about the request or you want it in a different format you can modify
249-
functions at the bottom of ``adafruit_httpserver/server.py`` that start with ``_debug_...``.
249+
{client_ip} -- "{request_method} {path}" {request_size} -- "{response_status}" {response_size}
250+
251+
If you need more information about the server or request, or you want it in a different format you can modify
252+
functions at the bottom of ``adafruit_httpserver/server.py`` and ``adafruit_httpserver/response.py`` that
253+
start with ``_debug_...``.
250254

251255
NOTE:
252256
*This is an advanced usage that might change in the future. It is not recommended to modify other parts of the code.*

0 commit comments

Comments
 (0)