-
Notifications
You must be signed in to change notification settings - Fork 34
/
request.py
64 lines (49 loc) · 1.79 KB
/
request.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import uuid
import structlog
import traceback
from .. import signals
logger = structlog.getLogger(__name__)
class RequestMiddleware(object):
""" ``RequestMiddleware`` adds request metadata to ``structlog``'s logger context automatically.
>>> MIDDLEWARE = [
... # ...
... 'django_structlog.middlewares.RequestMiddleware',
... ]
"""
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
from ipware import get_client_ip
request_id = str(uuid.uuid4())
with structlog.threadlocal.tmp_bind(logger):
logger.bind(request_id=request_id)
if hasattr(request, "user"):
logger.bind(user_id=request.user.id)
ip, routable = get_client_ip(request)
logger.bind(ip=ip)
signals.bind_extra_request_metadata.send(
sender=self.__class__, request=request, logger=logger
)
logger.info(
"request_started",
request=request,
user_agent=request.META.get("HTTP_USER_AGENT"),
)
try:
response = self.get_response(request)
except Exception as e:
traceback_object = e.__traceback__
formatted_traceback = traceback.format_tb(traceback_object)
logger.error(
"request_failed",
error_message=str(e),
error_traceback=formatted_traceback,
code=500,
request=request,
)
raise
else:
logger.info(
"request_finished", code=response.status_code, request=request
)
return response