Skip to content

Commit d8a88da

Browse files
browniebrokelnagel
authored andcommitted
Optimise status code conditions
The current conditions to match which level of log to use are more expensive that they should be. Instead of building a range object and do a lookup in it, which -in the worst case- can go through 100 of elements, it's 2x faster to compare with the 2 integers of the bound: ``` >>> import timeit >>> timeit.timeit("x in range(400, 500)", setup="from random import randint;x = randint(100, 1000)") 0.08440266699471977 >>> timeit.timeit("400 <= x < 500", setup="from random import randint;x = randint(100, 1000)") 0.0354189580102684 ``` As this middleware runs on every request, and info logs go through the if + elif condition, I think this small optimisation, while not life changing, is nice to have.
1 parent bdc448d commit d8a88da

File tree

1 file changed

+2
-2
lines changed

1 file changed

+2
-2
lines changed

django_datadog_logger/middleware/request_log.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ def log_response(self, request, response):
2626
duration_seconds = time.time() - request.request_start_time
2727
log_entry_dict["duration"] = duration_seconds * 1000000000.0
2828

29-
if response.status_code in range(400, 500):
29+
if 400 <= response.status_code < 500:
3030
log_entry_dict["error.kind"] = response.status_code
3131
log_entry_dict["error.message"] = response.reason_phrase
3232
if hasattr(response, "data") and isinstance(response.data, (list, dict, ReturnDict)):
@@ -35,7 +35,7 @@ def log_response(self, request, response):
3535
f"HTTP {response.status_code} {response.reason_phrase}",
3636
extra=log_entry_dict,
3737
)
38-
elif response.status_code in range(500, 600):
38+
elif 500 <= response.status_code < 600:
3939
log_entry_dict["error.kind"] = response.status_code
4040
log_entry_dict["error.message"] = response.reason_phrase
4141
logger.error(

0 commit comments

Comments
 (0)