Skip to content

feat: reduce http requests logs #1863

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open

feat: reduce http requests logs #1863

wants to merge 1 commit into from

Conversation

ab-smith
Copy link
Contributor

@ab-smith ab-smith commented Apr 15, 2025

Summary by CodeRabbit

  • Chores
    • Adjusted logging behavior to display more detailed information for certain request events in debug logs.

Copy link
Contributor

coderabbitai bot commented Apr 15, 2025

Walkthrough

A new function, lower_request_log_level, has been introduced to the logging configuration in the settings file. This function modifies the log level to "debug" for events of type "request_started" or "request_finished" and prints their event dictionaries to standard output. The function is integrated into the structlog processor chain, positioned after the log level is added and before positional argument formatting. No other changes to the logging configuration or application logic are present.

Changes

File(s) Change Summary
backend/ciso_assistant/settings.py Added lower_request_log_level function and inserted it into the structlog processor chain.

Sequence Diagram(s)

sequenceDiagram
    participant Django
    participant Logger
    participant lower_request_log_level

    Django->>Logger: Emit log event (e.g., request_started/request_finished)
    Logger->>lower_request_log_level: Process event_dict
    lower_request_log_level->>Logger: Modify log level to debug (if applicable), print event_dict
    Logger-->>Django: Continue logging with updated event_dict
Loading

Poem

In the logs where requests begin and end,
A rabbit hops in, a helpful friend.
With a whisper, it lowers the log’s loud call,
Printing the details, catching them all.
Now every request, both start and close,
Is debugged with care, as the rabbit knows!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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 generate docstrings to generate docstrings for this 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
Contributor

@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: 2

🧹 Nitpick comments (2)
backend/ciso_assistant/settings.py (2)

91-91: Consider making request debug logging optional

Adding this processor to the main structlog configuration means all request logs will be printed and downgraded to debug level in all environments.

If this is intended for temporary debugging, consider making it conditional:

        structlog.stdlib.add_logger_name,
        structlog.stdlib.add_log_level,
-        lower_request_log_level,
+        # Only include the processor if DEBUG_REQUESTS is enabled
+        *([] if os.environ.get("DEBUG_REQUESTS", "False") != "True" else [lower_request_log_level]),
        structlog.stdlib.PositionalArgumentsFormatter(),

Alternatively, you could implement this as middleware if it's intended for development use only.


43-91: Document the purpose of the lower_request_log_level function

The function lacks documentation explaining its purpose and when it should be used.

Add a docstring to clarify the function's intended use:

def lower_request_log_level(logger, method_name, event_dict):
+    """
+    Intercepts request_started and request_finished events and lowers their log level to debug.
+    
+    This function helps debug request processing by ensuring Django's request logs are 
+    visible even when the application's log level is set higher than DEBUG.
+    
+    Args:
+        logger: The logger instance
+        method_name: The logging method being called
+        event_dict: The structlog event dictionary
+    
+    Returns:
+        Modified event dictionary with adjusted log level for request events
+    """
    if event_dict.get("event") in {"request_started", "request_finished"}:
        print(event_dict)
        event_dict["level"] = "debug"
    return event_dict
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1cb9253 and 0840d20.

📒 Files selected for processing (1)
  • backend/ciso_assistant/settings.py (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (11)
  • GitHub Check: startup-docker-compose-test
  • GitHub Check: test (3.12)
  • GitHub Check: startup-functional-test (3.12)
  • GitHub Check: enterprise-startup-functional-test (3.12)
  • GitHub Check: functional-tests (3.12, chromium)
  • GitHub Check: enterprise-startup-docker-compose-test
  • GitHub Check: Analyze (python)
  • GitHub Check: build (3.12)
  • GitHub Check: enterprise-functional-tests (3.12, chromium)
  • GitHub Check: ruff (3.12)
  • GitHub Check: Analyze (javascript-typescript)

Comment on lines +43 to +47
def lower_request_log_level(logger, method_name, event_dict):
if event_dict.get("event") in {"request_started", "request_finished"}:
print(event_dict)
event_dict["level"] = "debug"
return event_dict
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify logging performance impact

The current implementation adds a print statement to every request, which could affect performance in high-traffic scenarios.


🏁 Script executed:

#!/bin/bash
# Check if we have any middleware that would generate request_started/request_finished events
# We're looking for the RequestMiddleware from django_structlog

echo "Checking for RequestMiddleware in the middleware configuration:"
# Check for RequestMiddleware in MIDDLEWARE
grep -n "RequestMiddleware" backend/ciso_assistant/settings.py

echo "Checking Django settings for log level:"
# Check the configured log level to understand the environment
grep -n "LOG_LEVEL" backend/ciso_assistant/settings.py

Length of output: 545


Performance Impact: Adjust Logging Behavior

The implementation currently uses a print statement in the lower_request_log_level function for request_started and request_finished events. With the django_structlog.middlewares.RequestMiddleware active, this hard-coded output may degrade performance under high traffic. Consider replacing the print(event_dict) with a logging call (e.g., logger.debug(event_dict)) that respects the LOG_LEVEL configuration to control output in production environments.


🛠️ Refactor suggestion

Reconsider using print() for request logging in production

The function lower_request_log_level prints entire event dictionaries to stdout, which could:

  1. Create excessive console output in high-traffic environments
  2. Potentially expose sensitive request information
  3. Impact performance when processing many requests

Consider making this debug behavior configurable with an environment variable and using the structured logger instead of print:

-def lower_request_log_level(logger, method_name, event_dict):
-    if event_dict.get("event") in {"request_started", "request_finished"}:
-        print(event_dict)
-        event_dict["level"] = "debug"
-    return event_dict
+def lower_request_log_level(logger, method_name, event_dict):
+    if event_dict.get("event") in {"request_started", "request_finished"}:
+        # Only modify log level when DEBUG_REQUESTS env var is enabled
+        if os.environ.get("DEBUG_REQUESTS", "False") == "True":
+            # Use existing logger instead of print
+            if LOG_LEVEL != "debug":
+                structlog.getLogger(__name__).debug(
+                    "Forcing request log to debug level", 
+                    **event_dict
+                )
+            event_dict["level"] = "debug"
+    return event_dict
📝 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
def lower_request_log_level(logger, method_name, event_dict):
if event_dict.get("event") in {"request_started", "request_finished"}:
print(event_dict)
event_dict["level"] = "debug"
return event_dict
def lower_request_log_level(logger, method_name, event_dict):
if event_dict.get("event") in {"request_started", "request_finished"}:
# Only modify log level when DEBUG_REQUESTS env var is enabled
if os.environ.get("DEBUG_REQUESTS", "False") == "True":
# Use existing logger instead of print
if LOG_LEVEL != "debug":
structlog.getLogger(__name__).debug(
"Forcing request log to debug level",
**event_dict
)
event_dict["level"] = "debug"
return event_dict

@ab-smith ab-smith changed the title wip feat: reduce http requests logs Apr 15, 2025
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.

1 participant