Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Middleware support #70

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions rest_framework_tracking/middleware.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@

from django.utils.deprecation import MiddlewareMixin
from .mixins import LoggingMixin


from rest_framework.views import APIView


class DrfTrackingMiddleware(MiddlewareMixin):
"""Log Every Activity of every Request

"""
drf_logging = LoggingMixin()

def _convert_django_request_to_drf_request_object(self, request):
"""convert Django `httpRequest` object into DRF request object

:param request: Django Http Request Object
:return: DRF request object
"""
return APIView().initialize_request(request)

def process_request(self, request):
# Don;t log in case of superuser
if request.user.is_superuser:
return
rq = self._convert_django_request_to_drf_request_object(request)
self.drf_logging.initial(rq, middleware=True)

def process_exception(self, request, exception, *args, **kwargs):
"""
"""
# Don;t log in case of superuser

if request.user.is_superuser:
return exception
rq = self._convert_django_request_to_drf_request_object(request)

self.drf_logging.handle_excption(rq, exception, middleware=True)
return exception

def process_response(self, request, response):
# Don;t log in case of superuser
if request.user.is_superuser:
return response

rq = self._convert_django_request_to_drf_request_object(request)
self.drf_logging.finalize_response(rq, response, middleware=True)
return response
45 changes: 24 additions & 21 deletions rest_framework_tracking/mixins.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ class BaseLoggingMixin(object):
"""Mixin to log requests"""
def initial(self, request, *args, **kwargs):
# get IP

ipaddr = request.META.get("HTTP_X_FORWARDED_FOR", None)
if ipaddr:
# X_FORWARDED_FOR returns client1, proxy1, proxy2,...
Expand All @@ -34,66 +35,68 @@ def initial(self, request, *args, **kwargs):
view_method = method.lower()

# create log
self.request.log = APIRequestLog(
qm = self._clean_data(request.query_params.dict())

self.log = APIRequestLog(
requested_at=now(),
path=request.path,
view=view_name,
view_method=view_method,
remote_addr=ipaddr,
host=request.get_host(),
method=request.method,
query_params=self._clean_data(request.query_params.dict()),
query_params=qm,
)

# regular initial, including auth check
super(BaseLoggingMixin, self).initial(request, *args, **kwargs)
if kwargs.get('middleware') is not True:
super(BaseLoggingMixin, self).initial(request, *args, **kwargs)

# add user to log after auth
user = request.user
if user.is_anonymous():
user = None
self.request.log.user = user
self.log.user = user

# get data dict
try:
# Accessing request.data *for the first time* parses the request body, which may raise
# ParseError and UnsupportedMediaType exceptions. It's important not to swallow these,
# as (depending on implementation details) they may only get raised this once, and
# DRF logic needs them to be raised by the view for error handling to work correctly.
self.request.log.data = self._clean_data(self.request.data.dict())
self.log.data = self._clean_data(request.data.dict())
except AttributeError: # if already a dict, can't dictify
self.request.log.data = self._clean_data(self.request.data)

def handle_exception(self, exc):
# basic handling
response = super(BaseLoggingMixin, self).handle_exception(exc)
self.log.data = self._clean_data(request.data)

def handle_exception(self, exc, **kwargs):
# log error
if hasattr(self.request, 'log'):
self.request.log.errors = traceback.format_exc()
if hasattr(self, 'log'):
self.log.errors = traceback.format_exc()

# return
return response
# basic handling
if kwargs.get('middleware') is not True:
return super(BaseLoggingMixin, self).handle_exception(exc)

def finalize_response(self, request, response, *args, **kwargs):
# regular finalize response
response = super(BaseLoggingMixin, self).finalize_response(request, response, *args, **kwargs)
if kwargs.get('middleware') is not True:
response = super(BaseLoggingMixin, self).finalize_response(request, response, *args, **kwargs)

# check if request is being logged
if not hasattr(self.request, 'log'):
if not hasattr(self, 'log'):
return response

# compute response time
response_timedelta = now() - self.request.log.requested_at
response_timedelta = now() - self.log.requested_at
response_ms = int(response_timedelta.total_seconds() * 1000)

# save to log
if (self._should_log(request, response)):
self.request.log.response = response.rendered_content
self.request.log.status_code = response.status_code
self.request.log.response_ms = response_ms
self.log.response = response.rendered_content
self.log.status_code = response.status_code
self.log.response_ms = response_ms
try:
self.request.log.save()
self.log.save()
except Exception:
# ensure that a DB error doesn't prevent API call to continue as expected
pass
Expand Down