Skip to content

Replace print statements with proper logging in peer_challenge_views.py#1021

Open
Diegomed11 wants to merge 3 commits intoalphaonelabs:mainfrom
Diegomed11:fix/replace-print-with-logging-peer-challenges
Open

Replace print statements with proper logging in peer_challenge_views.py#1021
Diegomed11 wants to merge 3 commits intoalphaonelabs:mainfrom
Diegomed11:fix/replace-print-with-logging-peer-challenges

Conversation

@Diegomed11
Copy link

@Diegomed11 Diegomed11 commented Mar 11, 2026

Description

Replaced all print() calls in web/peer_challenge_views.py with Python's logging module. Debug-level messages use logger.debug() and unexpected states (missing invitations, status mismatches) use logger.warning(). This avoids print statements in production code and follows Python logging best practices.

Related issues

No existing issue — found print statements during code review.

Checklist

  • Did you run the pre-commit? (If not, your PR will most likely not pass — please ensure it passes pre-commit)
  • Did you test the change? (Ensure you didn’t just prompt the AI and blindly commit — test the code and confirm it works)
  • [/ ] Added screenshots to the PR description (if applicable)

Replace print statements with proper logging in peer_challenge_views.py

Purpose

Replace debug print() calls in web/peer_challenge_views.py with Python's logging to follow best practices and improve observability in production.

Key Changes

  • Added module-level logger:
    • import logging; logger = logging.getLogger(name)
  • Replaced print() with logger.debug() for routine debug information:
    • challenge_list(): logs total completed challenges and per-challenge details
    • take_challenge(): logs user and challenge being taken
    • complete_challenge(): logs completion start and user_quiz details
  • Replaced print-based error/debug checks with logger.warning():
    • complete_challenge(): warns when no invitation is found and logs invitations with unexpected statuses
  • Preserved existing control flow, user-facing messages (Django messages), and behavior — only logging calls were changed.
  • Moved logging import to the top of the file to comply with PEP 8.

Impact

  • No functional or API changes; behavior and UX unchanged.
  • Improved logging integration makes debugging and monitoring easier without printing to stdout.
  • Changes are isolated to a single file.

Statistics

  • Lines changed: +13 / -9
  • Files changed: 1 (web/peer_challenge_views.py)

@github-actions
Copy link
Contributor

👀 Peer Review Required

Hi @Diegomed11! This pull request does not yet have a peer review.

Before this PR can be merged, please request a review from one of your peers:

  • Go to the PR page and click "Reviewers" on the right sidebar.
  • Select a team member or contributor to review your changes.
  • Once they approve, this reminder will be automatically removed.

Thank you for contributing! 🎉

@github-actions github-actions bot added the files-changed: 1 PR changes 1 file label Mar 11, 2026
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 11, 2026

Warning

Rate limit exceeded

@Diegomed11 has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 21 minutes and 18 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository: alphaonelabs/coderabbit/.coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: f8515f8a-7fab-4b02-84cc-d093065fdf75

📥 Commits

Reviewing files that changed from the base of the PR and between 9dffc17 and bc6e4db.

📒 Files selected for processing (1)
  • web/peer_challenge_views.py

Note

.coderabbit.yaml has unrecognized properties

CodeRabbit is using all valid settings from your configuration. Unrecognized properties (listed below) have been ignored and may indicate typos or deprecated fields that can be removed.

⚠️ Parsing warnings (1)
Validation error: Unrecognized key(s) in object: 'tools'
⚙️ Configuration instructions
  • Please see the configuration documentation for more information.
  • You can also validate your configuration using the online YAML validator.
  • 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

Walkthrough

Replaced print-based debug outputs in web/peer_challenge_views.py with Python logging by adding a module-level logger and converting prints to logger.debug()/logger.warning() across challenge_list, take_challenge, and complete_challenge while leaving control flow and user-facing messages unchanged.

Changes

Cohort / File(s) Summary
Logging Infrastructure Migration
web/peer_challenge_views.py
Added import logging and a module-level logger. Replaced print() debug statements with logger.debug() and used logger.warning() for missing/inconsistent invitation cases. No logic branches or user-facing messages were altered.

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~5 minutes

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately and concisely describes the main change: replacing print statements with logging in peer_challenge_views.py, which aligns perfectly with the changeset.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
📝 Coding Plan
  • Generate coding plan for human review comments

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

Comment @coderabbitai help to get the list of available commands and usage tips.

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: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
web/peer_challenge_views.py (1)

41-47: 🧹 Nitpick | 🔵 Trivial

Consider using lazy % formatting instead of f-strings in logging statements.

The static analysis tool (Ruff G004) correctly identifies that f-strings in logging are evaluated eagerly, even when the log level is disabled. For better performance, especially in code paths that execute frequently, use lazy formatting:

# Instead of:
logger.debug(f"Total completed challenges: {completed_challenges.count()}")

# Use:
logger.debug("Total completed challenges: %d", completed_challenges.count())

This applies to all logging statements in this file (lines 41, 43-47, 184, 221, 222, 233, 239, 245, 259).

That said, for debug-level logging that's typically disabled in production, this is a minor optimization. The current implementation is functionally correct and perfectly readable — addressing this is optional but would silence the linter warnings and align with Python logging best practices.

♻️ Example fix for lazy formatting
 # Debug logging
-logger.debug(f"Total completed challenges: {completed_challenges.count()}")
+logger.debug("Total completed challenges: %d", completed_challenges.count())
 for challenge in completed_challenges:
-    logger.debug(
-        f"Challenge: {challenge.challenge.title}, "
-        f"Updated at: {challenge.updated_at}, "
-        f"User Quiz: {challenge.user_quiz_id}"
-    )
+    logger.debug(
+        "Challenge: %s, Updated at: %s, User Quiz: %s",
+        challenge.challenge.title,
+        challenge.updated_at,
+        challenge.user_quiz_id,
+    )
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@web/peer_challenge_views.py` around lines 41 - 47, Replace the eager f-string
logging with lazy formatting calls to avoid unnecessary string interpolation:
update the logger.debug calls (e.g., the one using completed_challenges.count()
and the loop logging challenge.challenge.title, challenge.updated_at,
challenge.user_quiz_id) to use logger.debug with a format string and positional
arguments (e.g., "Total completed challenges: %d", completed_challenges.count())
and similarly for the per-challenge message, and apply the same change to the
other debug sites flagged (lines noted in the comment) so all logger.debug
invocations use lazy formatting instead of f-strings.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@web/peer_challenge_views.py`:
- Around line 11-13: Move the standard-library import "import logging" to the
top of the module so it appears before any third-party or local imports; ensure
the existing logger = logging.getLogger(__name__) remains where it is and that
no duplicate logging imports are introduced—look for the "import logging"
statement and the "logger" variable in this file (peer_challenge_views.py) and
reorder so "import logging" is in the module's top import block following PEP
8/isort conventions.

---

Outside diff comments:
In `@web/peer_challenge_views.py`:
- Around line 41-47: Replace the eager f-string logging with lazy formatting
calls to avoid unnecessary string interpolation: update the logger.debug calls
(e.g., the one using completed_challenges.count() and the loop logging
challenge.challenge.title, challenge.updated_at, challenge.user_quiz_id) to use
logger.debug with a format string and positional arguments (e.g., "Total
completed challenges: %d", completed_challenges.count()) and similarly for the
per-challenge message, and apply the same change to the other debug sites
flagged (lines noted in the comment) so all logger.debug invocations use lazy
formatting instead of f-strings.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository: alphaonelabs/coderabbit/.coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 99052259-579c-4183-ba01-aa777c83a723

📥 Commits

Reviewing files that changed from the base of the PR and between c94caf8 and e345445.

📒 Files selected for processing (1)
  • web/peer_challenge_views.py

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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
web/peer_challenge_views.py (1)

41-47: 🧹 Nitpick | 🔵 Trivial

Consider using lazy string formatting for logging statements.

The static analysis tool (Ruff G004) flags f-string usage in logging calls. While f-strings work perfectly fine, they're evaluated eagerly—meaning the string interpolation happens even when the log level is disabled (e.g., debug logs in production). Using %-style lazy formatting defers interpolation until the message is actually logged, which can improve performance when debug logging is turned off.

This applies to all logging statements in this file (lines 41, 184, 221, 222, 233, 239, 245, 259).

📝 Example of lazy formatting for this block
-    logger.debug(f"Total completed challenges: {completed_challenges.count()}")
+    logger.debug("Total completed challenges: %d", completed_challenges.count())
     for challenge in completed_challenges:
-        logger.debug(
-            f"Challenge: {challenge.challenge.title}, "
-            f"Updated at: {challenge.updated_at}, "
-            f"User Quiz: {challenge.user_quiz_id}"
-        )
+        logger.debug(
+            "Challenge: %s, Updated at: %s, User Quiz: %s",
+            challenge.challenge.title,
+            challenge.updated_at,
+            challenge.user_quiz_id,
+        )

Similar changes would apply to other logging statements:

# Line 184
logger.debug("User %s taking challenge %d: %s", request.user.username, challenge.id, challenge.title)

# Lines 221-222
logger.debug("Completing challenge for user quiz %s", user_quiz_id)
logger.debug("User quiz details: completed=%s, score=%s", user_quiz.completed, user_quiz.score)

# Line 233
logger.warning("No invitation found for user %s and quiz %s", request.user, user_quiz.quiz)

# Line 239
logger.warning("Found invitations with different statuses: %s", [inv.status for inv in all_invitations])

# Line 245
logger.debug("Found invitation: %s, current status: %s", invitation.id, invitation.status)

# Line 259
logger.debug("Pending invitations for challenge %s: %s", challenge.id, pending_invitations)

That said, this is a "good-to-have" improvement rather than a blocker. The current implementation is functionally correct and a clear improvement over the previous print() statements!

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@web/peer_challenge_views.py` around lines 41 - 47, The logger.debug/warning
calls in peer_challenge_views.py (e.g., the block logging completed_challenges
and other debug lines referenced: logger.debug at the top loop and the
statements flagged at lines 184, 221, 222, 233, 239, 245, 259) use f-strings
which evaluate eagerly; replace those f-strings with lazy %-style formatting
(e.g., logger.debug("Total completed challenges: %s",
completed_challenges.count()) and logger.debug("Challenge: %s, Updated at: %s,
User Quiz: %s", challenge.challenge.title, challenge.updated_at,
challenge.user_quiz_id)) and similarly convert the other
logger.debug/logger.warning calls to use "%s" placeholders and separate
arguments so interpolation is deferred until the message is actually emitted;
update all occurrences in functions/methods in this file to follow the same
pattern.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@web/peer_challenge_views.py`:
- Around line 41-47: The logger.debug/warning calls in peer_challenge_views.py
(e.g., the block logging completed_challenges and other debug lines referenced:
logger.debug at the top loop and the statements flagged at lines 184, 221, 222,
233, 239, 245, 259) use f-strings which evaluate eagerly; replace those
f-strings with lazy %-style formatting (e.g., logger.debug("Total completed
challenges: %s", completed_challenges.count()) and logger.debug("Challenge: %s,
Updated at: %s, User Quiz: %s", challenge.challenge.title, challenge.updated_at,
challenge.user_quiz_id)) and similarly convert the other
logger.debug/logger.warning calls to use "%s" placeholders and separate
arguments so interpolation is deferred until the message is actually emitted;
update all occurrences in functions/methods in this file to follow the same
pattern.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository: alphaonelabs/coderabbit/.coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: e86b7b68-552b-465c-8a9d-ccd42bd7c07f

📥 Commits

Reviewing files that changed from the base of the PR and between e345445 and 9dffc17.

📒 Files selected for processing (1)
  • web/peer_challenge_views.py

@Diegomed11
Copy link
Author

Fixed in the latest commit. Moved import logging to the top of the file before third-party imports per PEP 8

@Diegomed11
Copy link
Author

@A1L13N this is ready for review. All CodeRabbit feedback has been addressed. Replaces print statements with proper logging in peer_challenge_views.py.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

files-changed: 1 PR changes 1 file

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant