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: Log post requests and sdk changes #400

Merged
merged 2 commits into from
Oct 15, 2024

Conversation

Ashutosh619-sudo
Copy link
Contributor

@Ashutosh619-sudo Ashutosh619-sudo commented Oct 14, 2024

Copy link

coderabbitai bot commented Oct 14, 2024

Walkthrough

The changes introduce a new middleware class, LogPostRequestMiddleware, to log incoming POST and PUT requests. It processes requests by logging the request path and body, handling errors during logging appropriately. Additionally, the middleware is integrated into the settings, updating the logging configuration to allow existing loggers, add a new formatter and handler, and define a logger for xerosdk.apis.api_base. The requirements.txt file is also updated to reflect new versions for the fyle and xerosdk packages.

Changes

File Path Change Summary
fyle_xero_api/logging_middleware.py Added LogPostRequestMiddleware class to log POST and PUT request details.
fyle_xero_api/settings.py Updated middleware list to include LogPostRequestMiddleware, modified logging settings, added new formatter and handler, and defined a new logger.
requirements.txt Updated fyle version from 0.37.0 to 0.37.2 and xerosdk version from 0.14.1 to 0.14.2.

Possibly related PRs

  • feat: Add middleware to log all post requests #397: This PR introduces the LogPostRequestMiddleware class and adds it to the middleware list, directly related to the changes made in the main PR which also adds the same middleware class and functionality for logging POST requests.

Suggested reviewers

  • ashwin1111
  • ruuushhh

🐇 In the meadow, where bunnies play,
A new log middleware brightens the day.
With POST and PUT, it keeps track,
Logging each request, no detail it lacks!
Hopping along, with versions anew,
Fyle and Xero, we welcome you! 🌼


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Outside diff range and nitpick comments (3)
fyle_xero_api/settings.py (2)

152-152: LGTM: Logging configuration improved

The changes to the logging configuration are well-structured and align with the PR objectives:

  1. Setting disable_existing_loggers to False is a good practice, ensuring all loggers remain active.
  2. The new "standard" formatter provides consistent log formatting.
  3. The "console" handler with the "standard" formatter ensures uniform log output.
  4. The new logger for "xerosdk.apis.api_base" at INFO level will capture SDK changes as intended.

These improvements will enhance the application's logging capabilities and make debugging easier.

Consider adding a comment explaining the purpose of the "xerosdk.apis.api_base" logger to improve code maintainability.

Also applies to: 162-165, 178-181, 212-216


Line range hint 301-301: Consider aligning environment variable name with setting name

The setting XERO_APP_URL is currently set to os.environ.get("APP_URL"). To improve clarity and maintain consistency, consider either:

  1. Renaming the environment variable to XERO_APP_URL, or
  2. Renaming the setting to APP_URL

This alignment will reduce potential confusion and make the code more maintainable.

fyle_xero_api/logging_middleware.py (1)

41-42: Use logger.exception() to capture full stack trace

When handling exceptions, using logger.exception() is more appropriate as it automatically includes the stack trace in the logs. This provides more context for debugging compared to logger.info().

Apply this diff to use logger.exception():

-            logger.info('Something went wrong when logging post call - %s', e)
+            logger.exception('An exception occurred while logging POST/PUT request')
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between fb5ff1a and 4ab4079.

📒 Files selected for processing (3)
  • fyle_xero_api/logging_middleware.py (2 hunks)
  • fyle_xero_api/settings.py (5 hunks)
  • requirements.txt (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • requirements.txt
🧰 Additional context used
🔇 Additional comments (4)
fyle_xero_api/settings.py (3)

61-61: LGTM: LogPostRequestMiddleware added correctly

The addition of LogPostRequestMiddleware at the beginning of the middleware list is appropriate. This placement ensures that incoming POST and PUT requests are logged before any other middleware processes them, aligning with the PR objective.


Line range hint 302-303: LGTM: New integration URLs added

The addition of XERO_INTEGRATION_APP_URL and INTEGRATIONS_APP_URL settings is noted. These seem to be related to the integration of Xero and potentially other services.

Could you provide more context on how these URLs will be used in the application? This information would be helpful for future maintenance and understanding the system architecture.


Line range hint 1-338: Summary: Changes align with PR objectives and improve logging

Overall, the changes to settings.py are well-implemented and align with the PR objectives:

  1. The addition of LogPostRequestMiddleware enables logging of POST and PUT requests.
  2. Updates to the logging configuration improve log consistency and capture SDK changes.
  3. New integration-related settings have been added.

These changes will enhance the application's logging capabilities and support integration with Xero. A few minor suggestions have been made to improve clarity and maintainability.

fyle_xero_api/logging_middleware.py (1)

30-44: Ensure middleware is properly integrated and ordered

For the middleware to function correctly, it must be added to the MIDDLEWARE list in settings.py. Additionally, the order of middleware can affect processing; ensure that LogPostRequestMiddleware is placed appropriately, especially in relation to other middleware that might modify the request.

Run the following script to confirm the middleware is included and check its position:

✅ Verification successful

Middleware is properly integrated in fyle_xero_api/settings.py.

The LogPostRequestMiddleware is listed in the MIDDLEWARE configuration at line 61 of fyle_xero_api/settings.py. Ensure that its position relative to other middleware components aligns with the desired request processing flow.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that LogPostRequestMiddleware is present in MIDDLEWARE setting.

# Test: Search for LogPostRequestMiddleware in settings.py. Expect: Middleware is listed.

grep -rn 'MIDDLEWARE' settings.py -A 20 | grep 'LogPostRequestMiddleware'

Length of output: 116


Script:

#!/bin/bash
# Description: Find all settings.py files and verify LogPostRequestMiddleware is included in MIDDLEWARE.

# Find all settings.py files in the repository
settings_files=$(fd 'settings\.py' .)

# Check each settings.py for LogPostRequestMiddleware in MIDDLEWARE
for file in $settings_files; do
    echo "Checking $file for LogPostRequestMiddleware..."
    grep -rn 'LogPostRequestMiddleware' "$file"
done

Length of output: 671

import logging
import traceback

from django.conf import settings
from django.http import HttpResponse

logger = logging.getLogger(__name__)

logger.level = logging.INFO
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid setting logger level directly in code

Setting the logger level directly within the code overrides the logging configuration specified in your Django settings, which can lead to inconsistent logging behavior across the application. It's better to configure logging levels using the LOGGING setting in settings.py.

Apply this diff to remove the direct setting of the logger's level:

-logger.level = logging.INFO
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
logger.level = logging.INFO

Comment on lines +34 to +38
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)
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Potential security risk: Logging request bodies may expose sensitive data

Logging full request bodies for POST and PUT requests can inadvertently capture sensitive information such as passwords, tokens, or personally identifiable information (PII). This can lead to security vulnerabilities and compliance issues.

Consider sanitizing the request body before logging or avoid logging the body entirely. If logging is necessary, ensure sensitive data is masked or excluded.

Apply this diff to log only the request path and method:

-            logger.info("POST request to %s: %s", request.path, request_body)
+            logger.info("Received %s request to %s", request.method, request.path)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
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)
if request.method in ['POST', 'PUT']:
try:
body_unicode = request.body.decode('utf-8')
request_body = json.loads(body_unicode)
logger.info("Received %s request to %s", request.method, request.path)

Comment on lines +34 to +43
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)
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Check 'Content-Type' header before parsing request body as JSON

Attempting to parse the request body as JSON without verifying the 'Content-Type' may result in errors if the body is not JSON-formatted (e.g., form data, XML). This can cause unnecessary exceptions and logging noise.

Modify the code to check if the 'Content-Type' is 'application/json' before attempting to parse:

 if request.method in ['POST', 'PUT']:
+    if request.content_type == 'application/json':
         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)
+            logger.info("Received JSON %s request to %s: %s", request.method, request.path, request_body)
         except (json.JSONDecodeError, UnicodeDecodeError):
             logger.warning("Failed to decode JSON request body for %s", request.path)
         except Exception as e:
-            logger.info('Something went wrong when logging post call - %s', e)
+            logger.exception('An exception occurred while logging JSON request body')
+    else:
+        logger.info("Received %s request to %s with non-JSON content", request.method, request.path)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
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)
if request.method in ['POST', 'PUT']:
if request.content_type == 'application/json':
try:
body_unicode = request.body.decode('utf-8')
request_body = json.loads(body_unicode)
logger.info("Received JSON %s request to %s: %s", request.method, request.path, request_body)
except (json.JSONDecodeError, UnicodeDecodeError):
logger.warning("Failed to decode JSON request body for %s", request.path)
except Exception as e:
logger.exception('An exception occurred while logging JSON request body')
else:
logger.info("Received %s request to %s with non-JSON content", request.method, request.path)
response = self.get_response(request)

Copy link

Tests Skipped Failures Errors Time
163 0 💤 0 ❌ 0 🔥 1m 9s ⏱️

@Ashutosh619-sudo Ashutosh619-sudo merged commit 020f79f into master Oct 15, 2024
2 checks passed
Ashutosh619-sudo added a commit that referenced this pull request Oct 15, 2024
* feat: Log post requests and sdk changes

* pylint resolved
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants