Skip to content

Instantly share code, notes, and snippets.

@elcolie
Created October 6, 2017 09:31
Show Gist options
  • Save elcolie/5d9b1a2f890a0efcb46fdb95c0e90908 to your computer and use it in GitHub Desktop.
Save elcolie/5d9b1a2f890a0efcb46fdb95c0e90908 to your computer and use it in GitHub Desktop.
Customized middleware
import collections
import json
import logging
import uuid
request_logger = logging.getLogger('django')
class LoggingMiddleware:
"""
Provides simple logging of requests and responses
I decided to start logging at RESTful API first then I will expand it later
"""
_initial_http_body = None
__uuid = None
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
self.process_request(request)
self.process_response(request, response)
return response
def process_request(self, request):
if request.path.startswith('/api/'):
data = collections.OrderedDict()
data["user"] = request.user.username
data["path"] = request.path
data["method"] = request.method
data["content-type"] = request.content_type
if request.method == 'GET':
data['GET'] = request.GET
elif request.method == 'POST':
data['POST'] = request.POST
elif request.method == 'DELETE':
pass
self.__uuid = str(uuid.uuid4())
request_logger.info(f'{self.__uuid} {json.dumps(data)}')
def process_response(self, request, response):
"""
Adding request and response logging
"""
if request.path.startswith('/api/'):
try:
response.data
except Exception:
msg = f'{self.__uuid} {response.status_code}'
else:
msg = f'{self.__uuid} {response.status_code} {response.data}'
finally:
request_logger.info(msg)
return response
def process_exception(self, request, exception):
request_logger.info(f"{self.__uuid} {exception}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment