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

feat: Add middleware to log all post requests #397

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
20 changes: 20 additions & 0 deletions fyle_xero_api/logging_middleware.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import json
import logging
import traceback

Expand Down Expand Up @@ -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
Comment on lines +35 to +47
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Improve error handling and logging in the __call__ method

The current implementation is good, but there are a few areas for improvement:

  1. The general except Exception block on line 43 could be more specific to avoid catching unexpected errors.
  2. The warning log on line 42 could include more details about the failure, such as the exception message.

Consider refactoring the method as follows:

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 as e:
            logger.warning("Failed to decode JSON in POST request body for %s: %s", request.path, str(e))
        except UnicodeDecodeError as e:
            logger.warning("Failed to decode Unicode in POST request body for %s: %s", request.path, str(e))
        except Exception as e:
            logger.error("Unexpected error when logging POST request to %s: %s", request.path, str(e))

    response = self.get_response(request)
    return response

This refactoring:

  1. Separates the JSONDecodeError and UnicodeDecodeError exceptions for more specific error handling.
  2. Includes the exception message in the warning logs for better debugging.
  3. Changes the general exception log to an error level and includes more context.

1 change: 1 addition & 0 deletions fyle_xero_api/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
Loading