From 71f918a2bda99aada80d34f95bb62dfdd534d719 Mon Sep 17 00:00:00 2001 From: Ashutosh singh <55102089+Ashutosh619-sudo@users.noreply.github.com> Date: Sun, 13 Oct 2024 20:13:41 +0530 Subject: [PATCH] feat: Add middleware to log all post requests (#397) * feat: Add middleware to log all post requests * resolved pylint --- fyle_xero_api/logging_middleware.py | 20 ++++++++++++++++++++ fyle_xero_api/settings.py | 1 + 2 files changed, 21 insertions(+) diff --git a/fyle_xero_api/logging_middleware.py b/fyle_xero_api/logging_middleware.py index 9fb5391b..8d1c65b9 100644 --- a/fyle_xero_api/logging_middleware.py +++ b/fyle_xero_api/logging_middleware.py @@ -1,3 +1,4 @@ +import json import logging import traceback @@ -25,3 +26,22 @@ def process_exception(self, request, exception): logger.error(str(message).replace("\n", "")) return HttpResponse("Error processing the request.", status=500) + + +class LogPostRequestMiddleware: + def __init__(self, get_response): + self.get_response = get_response + + def __call__(self, request): + if request.method in ['POST', 'PUT']: + try: + body_unicode = request.body.decode('utf-8') + request_body = json.loads(body_unicode) + logger.info("POST request to %s: %s", request.path, request_body) + except (json.JSONDecodeError, UnicodeDecodeError): + logger.warning("Failed to decode POST request body for %s", request.path) + except Exception as e: + logger.info('Something went wrong when logging post call - %s', e) + + response = self.get_response(request) + return response diff --git a/fyle_xero_api/settings.py b/fyle_xero_api/settings.py index b21b5047..bd466436 100644 --- a/fyle_xero_api/settings.py +++ b/fyle_xero_api/settings.py @@ -60,6 +60,7 @@ MIDDLEWARE = [ "request_logging.middleware.LoggingMiddleware", "fyle_xero_api.logging_middleware.ErrorHandlerMiddleware", + "fyle_xero_api.logging_middleware.LogPostRequestMiddleware", "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", "corsheaders.middleware.CorsPostCsrfMiddleware",