Last active
September 10, 2024 20:08
-
-
Save SehgalDivij/1ca5c647c710a2c3a0397bce5ec1c1b4 to your computer and use it in GitHub Desktop.
Middleware in django to log all requests and responses(Inspired by another Github gist I cannot find the link to, now)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Middleware to log all requests and responses. | |
Uses a logger configured by the name of django.request | |
to log all requests and responses according to configuration | |
specified for django.request. | |
""" | |
# import json | |
import logging | |
from django.utils.deprecation import MiddlewareMixin | |
import socket | |
import time | |
import json | |
request_logger = logging.getLogger('django.request') | |
class RequestLogMiddleware(MiddlewareMixin): | |
"""Request Logging Middleware.""" | |
def __init__(self, *args, **kwargs): | |
"""Constructor method.""" | |
super().__init__(*args, **kwargs) | |
def process_request(self, request): | |
"""Set Request Start Time to measure time taken to service request.""" | |
if request.method in ['POST', 'PUT', 'PATCH']: | |
request.req_body = request.body | |
if str(request.get_full_path()).startswith('/api/'): | |
request.start_time = time.time() | |
def extract_log_info(self, request, response=None, exception=None): | |
"""Extract appropriate log info from requests/responses/exceptions.""" | |
log_data = { | |
'remote_address': request.META['REMOTE_ADDR'], | |
'server_hostname': socket.gethostname(), | |
'request_method': request.method, | |
'request_path': request.get_full_path(), | |
'run_time': time.time() - request.start_time, | |
} | |
if request.method in ['PUT', 'POST', 'PATCH']: | |
log_data['request_body'] = json.loads( | |
str(request.req_body, 'utf-8')) | |
if response: | |
if response['content-type'] == 'application/json': | |
response_body = response.content | |
log_data['response_body'] = response_body | |
return log_data | |
def process_response(self, request, response): | |
"""Log data using logger.""" | |
if request.method != 'GET': | |
if str(request.get_full_path()).startswith('/api/'): | |
log_data = self.extract_log_info(request=request, | |
response=response) | |
request_logger.debug(msg='', extra=log_data) | |
return response | |
def process_exception(self, request, exception): | |
"""Log Exceptions.""" | |
try: | |
raise exception | |
except Exception: | |
request_logger.exception(msg="Unhandled Exception") | |
return exception |
Ah Yes.
Thanks @naorye. made the change.
When I integrate it to django I get
django.core.exceptions.ImproperlyConfigured: WSGI application 'GoFish.wsgi.application' could not be loaded; Error importing module.
What am I doing wrong? I created a class and pasted your code and added it to middlewares..
This is old. I will check again and let you know.
On Fri, 21 Feb 2020 at 3:05 PM, bennibau ***@***.***> wrote:
When I integrate it to django I get
django.core.exceptions.ImproperlyConfigured: WSGI application
'GoFish.wsgi.application' could not be loaded; Error importing module.
What am I doing wrong? I created a class and pasted your code and added it
to middlewares..
—
You are receiving this because you authored the thread.
Reply to this email directly, view it on GitHub
<https://gist.github.com/1ca5c647c710a2c3a0397bce5ec1c1b4?email_source=notifications&email_token=AEHLCCFGA7K3S54QVFHXGT3RD6N45A5CNFSM4H4XMML2YY3PNVWWK3TUL52HS4DFVNDWS43UINXW23LFNZ2KUY3PNVWWK3TUL5UWJTQAGCLQ2#gistcomment-3184397>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/AEHLCCCDG24KNWLSB2ZGOB3RD6N45ANCNFSM4H4XMMLQ>
.
--
Sent from Gmail Mobile
No thanks, I used djang-logging middleware package and that worked fine for me
… Am 21.02.2020 um 14:56 schrieb Divij Sehgal ***@***.***>:
This is old. I will check again and let you know.
On Fri, 21 Feb 2020 at 3:05 PM, bennibau ***@***.***> wrote:
> When I integrate it to django I get
> django.core.exceptions.ImproperlyConfigured: WSGI application
> 'GoFish.wsgi.application' could not be loaded; Error importing module.
> What am I doing wrong? I created a class and pasted your code and added it
> to middlewares..
>
> —
> You are receiving this because you authored the thread.
> Reply to this email directly, view it on GitHub
> <https://gist.github.com/1ca5c647c710a2c3a0397bce5ec1c1b4?email_source=notifications&email_token=AEHLCCFGA7K3S54QVFHXGT3RD6N45A5CNFSM4H4XMML2YY3PNVWWK3TUL52HS4DFVNDWS43UINXW23LFNZ2KUY3PNVWWK3TUL5UWJTQAGCLQ2#gistcomment-3184397>,
> or unsubscribe
> <https://github.com/notifications/unsubscribe-auth/AEHLCCCDG24KNWLSB2ZGOB3RD6N45ANCNFSM4H4XMMLQ>
> .
>
--
Sent from Gmail Mobile
—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub <https://gist.github.com/1ca5c647c710a2c3a0397bce5ec1c1b4?email_source=notifications&email_token=ABUQO2VUCTXYAFLZF57ZWFTRD7MPJA5CNFSM4H4XMML2YY3PNVWWK3TUL52HS4DFVNDWS43UINXW23LFNZ2KUY3PNVWWK3TUL5UWJTQAGCMB4#gistcomment-3184670>, or unsubscribe <https://github.com/notifications/unsubscribe-auth/ABUQO2S2QUPFGC576WUXTSDRD7MPJANCNFSM4H4XMMLQ>.
Hi @bennibau, are you using this? https://github.com/Rhumbix/django-request-logging
No thanks, I used djang-logging middleware package and that worked fine for me
thanks
How do I configure this in the settings.py
?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Line 44 shouldn't it be
if response:
?