Skip to content

Commit 02df661

Browse files
committed
process PR feedback
1 parent 5008ad8 commit 02df661

File tree

20 files changed

+1012
-486
lines changed

20 files changed

+1012
-486
lines changed

.github/workflows/ci.yml

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,14 +15,21 @@ jobs:
1515
runs-on: ubuntu-latest
1616
strategy:
1717
matrix:
18-
python: ["3.7", "3.8", "3.9", "3.10"]
18+
python: ["3.8", "3.9", "3.10"]
1919
django: ["3.2", "4.1"]
20-
exclude:
21-
- python: "3.7"
22-
django: "4.1"
2320

2421
name: Run the test suite (Python ${{ matrix.python }}, Django ${{ matrix.django }})
2522

23+
services:
24+
postgres:
25+
image: postgres:14
26+
env:
27+
POSTGRES_HOST_AUTH_METHOD: trust
28+
ports:
29+
- 5432:5432
30+
# needed because the postgres container does not provide a healthcheck
31+
options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5
32+
2633
steps:
2734
- uses: actions/checkout@v3
2835
- uses: actions/setup-python@v4

README.rst

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -97,8 +97,16 @@ To use this with your project you need to follow these steps:
9797
}
9898
9999
LOG_OUTGOING_REQUESTS_DB_SAVE = True # save logs enabled/disabled based on the boolean value
100-
LOG_OUTGOING_REQUESTS_SAVE_BODY = True # save request/response body
101-
LOG_OUTGOING_REQUESTS_LOG_BODY_TO_STDOUT = True # log request/response body to STDOUT
100+
LOG_OUTGOING_REQUESTS_DB_SAVE_BODY = True # save request/response body
101+
LOG_OUTGOING_REQUESTS_EMIT_BODY = True # log request/response body
102+
LOG_OUTGOING_REQUESTS_CONTENT_TYPES = [
103+
"text/*",
104+
"application/json",
105+
"application/xml",
106+
"application/soap+xml",
107+
] # save request/response bodies with matching content type
108+
LOG_OUTGOING_REQUESTS_MAX_CONTENT_LENGTH = 524_288 # maximal size (in bytes) for the request/response body
109+
LOG_OUTGOING_REQUESTS_LOG_BODY_TO_STDOUT = True
102110
103111
104112
#. Run the migrations
@@ -115,8 +123,9 @@ To use this with your project you need to follow these steps:
115123
res = requests.get("https://httpbin.org/json")
116124
print(res.json())
117125
118-
#. Check stdout for the printable output, and navigate to ``/admin/log_outgoing_requests/outgoingrequestslog/`` to see
119-
the saved log records. The settings for saving logs can by overridden under ``/admin/log_outgoing_requests/outgoingrequestslogconfig/``.
126+
#. Check stdout for the printable output, and navigate to ``Admin > Miscellaneous > Outgoing Requests Logs``
127+
to see the saved log records. In order to override the settings for saving logs, navigate to
128+
``Admin > Miscellaneous > Outgoing Requests Log Configuration``.
120129

121130

122131
Local development

docs/quickstart.rst

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,8 +58,16 @@ Installation
5858
}
5959
6060
LOG_OUTGOING_REQUESTS_DB_SAVE = True # save logs enabled/disabled based on the boolean value
61-
LOG_OUTGOING_REQUESTS_SAVE_BODY = True # save request/response body
62-
LOG_OUTGOING_REQUESTS_LOG_BODY_TO_STDOUT = True # log request/response body to STDOUT
61+
LOG_OUTGOING_REQUESTS_DB_SAVE_BODY = True # save request/response body
62+
LOG_OUTGOING_REQUESTS_EMIT_BODY = True # log request/response body
63+
LOG_OUTGOING_REQUESTS_CONTENT_TYPES = [
64+
"text/*",
65+
"application/json",
66+
"application/xml",
67+
"application/soap+xml",
68+
] # save request/response bodies with matching content type
69+
LOG_OUTGOING_REQUESTS_MAX_CONTENT_LENGTH = 524_288 # maximal size (in bytes) for the request/response body
70+
LOG_OUTGOING_REQUESTS_LOG_BODY_TO_STDOUT = True
6371
6472
6573
#. Run ``python manage.py migrate`` to create the necessary database tables.

log_outgoing_requests/admin.py

Lines changed: 46 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,13 @@
1+
from django import forms
2+
from django.conf import settings
13
from django.contrib import admin
4+
from django.shortcuts import get_object_or_404
25
from django.utils.translation import gettext as _
36

47
from solo.admin import SingletonModelAdmin
58

69
from .models import OutgoingRequestsLog, OutgoingRequestsLogConfig
7-
8-
9-
@admin.display(description="Response body")
10-
def response_body(obj):
11-
return f"{obj}".upper()
10+
from .utils import decode
1211

1312

1413
@admin.register(OutgoingRequestsLog)
@@ -44,6 +43,7 @@ class OutgoingRequestsLogAdmin(admin.ModelAdmin):
4443
search_fields = ("url", "params", "hostname")
4544
date_hierarchy = "timestamp"
4645
show_full_result_count = False
46+
change_form_template = "log_outgoing_requests/change_form.html"
4747

4848
def has_add_permission(self, request):
4949
return False
@@ -54,6 +54,24 @@ def has_change_permission(self, request, obj=None):
5454
def query_params(self, obj):
5555
return obj.query_params
5656

57+
def change_view(self, request, object_id, extra_context=None):
58+
"""Decode request/response body and add to context for display"""
59+
60+
log = get_object_or_404(OutgoingRequestsLog, id=object_id)
61+
62+
log_req_body = decode(log.req_body, log.req_body_encoding)
63+
log_res_body = decode(log.res_body, log.res_body_encoding)
64+
65+
extra_context = extra_context or {}
66+
extra_context["log_req_body"] = log_req_body
67+
extra_context["log_res_body"] = log_res_body
68+
69+
return super().change_view(
70+
request,
71+
object_id,
72+
extra_context=extra_context,
73+
)
74+
5775
query_params.short_description = _("Query parameters")
5876

5977
class Media:
@@ -62,13 +80,28 @@ class Media:
6280
}
6381

6482

83+
class ConfigAdminForm(forms.ModelForm):
84+
class Meta:
85+
model = OutgoingRequestsLogConfig
86+
fields = "__all__"
87+
widgets = {"allowed_content_types": forms.CheckboxSelectMultiple}
88+
help_texts = {
89+
"save_to_db": _(
90+
"Whether request logs should be saved to the database (default: {default})."
91+
).format(default=settings.LOG_OUTGOING_REQUESTS_DB_SAVE),
92+
"save_body": _(
93+
"Wheter the body of the request and response should be logged (default: "
94+
"{default}). This option is ignored if 'Save Logs to database' is set to "
95+
"False."
96+
).format(default=settings.LOG_OUTGOING_REQUESTS_DB_SAVE_BODY),
97+
}
98+
99+
65100
@admin.register(OutgoingRequestsLogConfig)
66101
class OutgoingRequestsLogConfigAdmin(SingletonModelAdmin):
67-
fields = (
68-
"save_to_db",
69-
"save_body",
70-
)
71-
list_display = (
72-
"save_to_db",
73-
"save_body",
74-
)
102+
form = ConfigAdminForm
103+
104+
class Media:
105+
css = {
106+
"all": ("log_outgoing_requests/css/admin.css",),
107+
}

log_outgoing_requests/constants.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
from django.db import models
2+
from django.utils.translation import gettext_lazy as _
3+
4+
5+
class SaveLogsChoice(models.TextChoices):
6+
use_default = "use_default", _("Use default")
7+
yes = "yes", _("Yes")
8+
no = "no", _("No")
9+
10+
11+
class ContentType(models.TextChoices):
12+
audio = "audio/*", _("Audio")
13+
form_data = "multipart/form-data", _("Form data")
14+
json = "application/json", _("JSON")
15+
text = "text/*", ("Plain text & HTML")
16+
video = "video/*", _("Video")
17+
xml = "application/xml", _("XML")

log_outgoing_requests/formatters.py

Lines changed: 23 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -8,32 +8,37 @@ class HttpFormatter(logging.Formatter):
88
def _formatHeaders(self, d):
99
return "\n".join(f"{k}: {v}" for k, v in d.items())
1010

11-
def _formatBody(self, content: dict, request_or_response: str) -> str:
11+
def _formatBody(self, content: str, request_or_response: str) -> str:
1212
if settings.LOG_OUTGOING_REQUESTS_LOG_BODY_TO_STDOUT:
1313
return f"\n{request_or_response} body:\n{content}"
1414
return ""
1515

1616
def formatMessage(self, record):
1717
result = super().formatMessage(record)
18-
if record.name == "requests":
19-
result += textwrap.dedent(
20-
"""
21-
---------------- request ----------------
22-
{req.method} {req.url}
23-
{reqhdrs} {request_body}
2418

25-
---------------- response ----------------
26-
{res.status_code} {res.reason} {res.url}
27-
{reshdrs} {response_body}
19+
if record.name != "requests":
20+
return result
2821

22+
result += textwrap.dedent(
2923
"""
30-
).format(
31-
req=record.req,
32-
res=record.res,
33-
reqhdrs=self._formatHeaders(record.req.headers),
34-
reshdrs=self._formatHeaders(record.res.headers),
35-
request_body=self._formatBody(record.req.body, "Request"),
36-
response_body=self._formatBody(record.res.json(), "Response"),
37-
)
24+
---------------- request ----------------
25+
{req.method} {req.url}
26+
{reqhdrs} {request_body}
27+
28+
---------------- response ----------------
29+
{res.status_code} {res.reason} {res.url}
30+
{reshdrs} {response_body}
31+
32+
"""
33+
).format(
34+
req=record.req,
35+
res=record.res,
36+
reqhdrs=self._formatHeaders(record.req.headers),
37+
reshdrs=self._formatHeaders(record.res.headers),
38+
request_body=self._formatBody(record.req.body, "Request"),
39+
response_body=self._formatBody(
40+
record.res.content.decode("utf-8"), "Response"
41+
),
42+
)
3843

3944
return result

log_outgoing_requests/handlers.py

Lines changed: 26 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -2,70 +2,61 @@
22
import traceback
33
from urllib.parse import urlparse
44

5-
from django.conf import settings
6-
7-
ALLOWED_CONTENT_TYPES = [
8-
"application/json",
9-
"multipart/form-data",
10-
"text/html",
11-
"text/plain",
12-
"",
13-
None,
14-
]
5+
from .utils import get_encoding, is_content_admissible_for_saving
156

167

178
class DatabaseOutgoingRequestsHandler(logging.Handler):
189
def emit(self, record):
19-
from .models import OutgoingRequestsLogConfig
10+
from .models import OutgoingRequestsLog, OutgoingRequestsLogConfig
2011

2112
config = OutgoingRequestsLogConfig.get_solo()
2213

23-
if config.save_to_db or settings.LOG_OUTGOING_REQUESTS_DB_SAVE:
24-
from .models import OutgoingRequestsLog
25-
26-
trace = None
14+
if config.save_logs_enabled:
15+
trace = ""
2716

2817
# skip requests not coming from the library requests
2918
if not record or not record.getMessage() == "Outgoing request":
3019
return
3120

32-
# skip requests with non-allowed content
33-
request_content_type = record.req.headers.get("Content-Type", "")
34-
response_content_type = record.res.headers.get("Content-Type", "")
35-
36-
if not (
37-
request_content_type in ALLOWED_CONTENT_TYPES
38-
and response_content_type in ALLOWED_CONTENT_TYPES
39-
):
40-
return
41-
42-
safe_req_headers = record.req.headers.copy()
21+
scrubbed_req_headers = record.req.headers.copy()
4322

44-
if "Authorization" in safe_req_headers:
45-
safe_req_headers["Authorization"] = "***hidden***"
23+
if "Authorization" in scrubbed_req_headers:
24+
scrubbed_req_headers["Authorization"] = "***hidden***"
4625

4726
if record.exc_info:
4827
trace = traceback.format_exc()
4928

5029
parsed_url = urlparse(record.req.url)
5130
kwargs = {
5231
"url": record.req.url,
53-
"hostname": parsed_url.hostname,
32+
"hostname": parsed_url.netloc,
5433
"params": parsed_url.params,
5534
"status_code": record.res.status_code,
5635
"method": record.req.method,
57-
"req_content_type": record.req.headers.get("Content-Type", ""),
58-
"res_content_type": record.res.headers.get("Content-Type", ""),
5936
"timestamp": record.requested_at,
6037
"response_ms": int(record.res.elapsed.total_seconds() * 1000),
61-
"req_headers": self.format_headers(safe_req_headers),
38+
"req_headers": self.format_headers(scrubbed_req_headers),
6239
"res_headers": self.format_headers(record.res.headers),
6340
"trace": trace,
41+
"req_content_type": "",
42+
"res_content_type": "",
43+
"req_body": b"",
44+
"res_body": b"",
45+
"req_body_encoding": "",
46+
"res_body_encoding": record.res.encoding,
6447
}
6548

66-
if config.save_body or settings.LOG_OUTGOING_REQUESTS_SAVE_BODY:
67-
kwargs["req_body"] = (record.req.body,)
68-
kwargs["res_body"] = (record.res.json(),)
49+
if config.save_body_enabled:
50+
# check request
51+
if is_content_admissible_for_saving(record.req, config):
52+
kwargs["req_content_type"] = record.req.headers.get("Content-Type")
53+
kwargs["req_body"] = record.req.body or b""
54+
kwargs["req_body_encoding"] = get_encoding(record.req)
55+
56+
# check response
57+
if is_content_admissible_for_saving(record.res, config):
58+
kwargs["res_content_type"] = record.res.headers.get("Content-Type")
59+
kwargs["res_body"] = record.res.content or b""
6960

7061
OutgoingRequestsLog.objects.create(**kwargs)
7162

0 commit comments

Comments
 (0)