Skip to content

REFACTOR: Replace prints with proper logging#1036

Open
Diegomed11 wants to merge 4 commits intoalphaonelabs:mainfrom
Diegomed11:fix/remove-remaining-prints
Open

REFACTOR: Replace prints with proper logging#1036
Diegomed11 wants to merge 4 commits intoalphaonelabs:mainfrom
Diegomed11:fix/remove-remaining-prints

Conversation

@Diegomed11
Copy link

@Diegomed11 Diegomed11 commented Mar 19, 2026

Description

Replaced the remaining print() statements across the codebase (web/views.py, web/models.py, and web/quiz_views.py) with Python's logging module to follow production best practices. Used lazy formatting (%s) and appropriate log levels (logger.debug, logger.warning, logger.error) based on the context of each message. Also resolved flake8 linting errors regarding import order and spacing to ensure clean code.

Related issues

No existing issue — identified proactive technical debt/improvement during codebase exploration.

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)

Purpose

Refactor: replace direct print() statements with Python's logging module across the codebase to improve debugging, consistency, and adherence to best practices.

Key Changes

web/models.py

  • Added module-level logger (logger = logging.getLogger(__name__)) and imported logging.
  • Replaced print() calls in Session.fetch_coordinates() with logger.debug() for normal/invalid-coordinate paths.
  • Simplified exception handling and replaced in-function logger reinitialization with logger.exception() to log errors with tracebacks.
  • Minor import/whitespace cleanup.

web/quiz_views.py

  • Added module-level logger.
  • Replaced print(e) in exception handling with logger.error("An error occurred: %s", e) using lazy formatting.

web/views.py

  • Added/cleaned module-level import logging.
  • Replaced multiple print() statements with appropriate logging calls (logger.warning(), logger.debug(), logger.error(), and logger.exception()).
  • Handlers updated include Slack webhook warnings, form error logging, system status checks, Twitter posting errors, and contributor fetch errors.

Impact

  • No functional or control-flow changes; public/exported signatures remain unchanged.
  • Improves maintainability and observability by using the logging framework (supports levels, filtering, and, via logger.exception(), automatic tracebacks).
  • Flake8 import-order/spacing issues addressed.
  • Per reviewer note and subsequent commit(s), exception handlers were updated broadly to use logger.exception() in except blocks to ensure stack traces are captured.

Size / Review Notes

  • Small, low-risk refactor across three files. Review focus: correct log levels, consistent lazy formatting, and verification that no print() calls remain.

@github-actions github-actions bot added the files-changed: 3 PR changes 3 files label Mar 19, 2026
@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! 🎉

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 19, 2026

Warning

Rate limit exceeded

@Diegomed11 has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 10 minutes and 2 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: a40ef8e0-548b-4bec-947d-cbebd0f520d7

📥 Commits

Reviewing files that changed from the base of the PR and between 4912a73 and 28fcc00.

📒 Files selected for processing (1)
  • web/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 stdout prints with structured Python logging across three web modules, adding import logging and logger = logging.getLogger(__name__) where missing; substituted print calls with appropriate logger levels (debug, warning, error/exception) without changing control flow or public APIs. (≤50 words)

Changes

Cohort / File(s) Summary
Models (geolocation)
web/models.py
Added import logging and logger = logging.getLogger(__name__); replaced print(...) with logger.debug(...) for coordinate saves and used logger.exception(...) in the exception path of Session.fetch_coordinates.
Quiz views
web/quiz_views.py
Added module-level logger and replaced print(e) in add_question error handling with logger.error("An error occurred: %s", e).
General views / handlers
web/views.py
Added module-level logger and replaced various print calls with logger.warning, logger.debug, and logger.exception for Slack webhook checks, form validation, SendGrid/Twitter/connectivity errors, and contributor fetch failures.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 62.50% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately captures the main refactoring objective: replacing print statements with logging across multiple files in the codebase.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

Tip

CodeRabbit can suggest fixes for GitHub Check annotations.

Configure the reviews.tools.github-checks setting to adjust the time to wait for GitHub Checks to complete.

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

🤖 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/models.py`:
- Around line 498-499: Replace the manual error logging in the except block that
calls logger.error("Error geocoding session %s location '%s': %s", self.id,
self.location, str(e)) with logger.exception so the full stack trace is
recorded; locate the exception handler in web/models.py that references self.id,
self.location and the exception variable e (the geocoding error path) and change
the logging call to use logger.exception with an appropriate message (omit
str(e) since logger.exception captures the exception and traceback
automatically).
- Around line 494-497: The logger.debug call incorrectly passes two f-strings as
separate positional arguments so the second is ignored; replace it with a single
lazy-formatted logging call such as logger.debug("Skipping session %s due to
invalid coordinates: lat=%s, lng=%s", self.id, self.latitude, self.longitude) to
use the logging module's %s placeholders and keep consistent lazy formatting for
the logger.debug invocation that references self.id, self.latitude and
self.longitude.

In `@web/quiz_views.py`:
- Around line 187-190: Replace the logger.error call inside the except block
that currently logs "An error occurred: %s" with logger.exception so the stack
trace is captured automatically; locate the except handler in web/quiz_views.py
where logger.error("An error occurred: %s", e) is used, change it to
logger.exception("An error occurred") (do not pass the exception object), and
keep the subsequent raise to re-raise the exception.

In `@web/views.py`:
- Line 8116: Replace uses of logger.error("Error posting tweet: %s", e) inside
the exception handlers with logger.exception(...) so the traceback is captured
automatically; locate the catch blocks that call logger.error with the exception
variable (e.g., the "Error posting tweet" logger.error call and the similar
logger.error call near the other reported location) and change them to
logger.exception("Error posting tweet") (or an appropriate message) without
manually formatting the exception variable.

ℹ️ Review info
⚙️ Run configuration

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

Review profile: ASSERTIVE

Plan: Pro

Run ID: 175e5be7-b911-4d2a-a346-b394dc02021f

📥 Commits

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

📒 Files selected for processing (3)
  • web/models.py
  • web/quiz_views.py
  • web/views.py

Copy link
Contributor

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

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

This PR has 2 unresolved review conversations. Please resolve them before this PR can be merged.

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.

♻️ Duplicate comments (1)
web/models.py (1)

494-497: ⚠️ Potential issue | 🟠 Major

Bug: The second f-string argument is being silently discarded.

This issue was flagged in a previous review but appears to still be present. When you pass multiple positional arguments to logger.debug(), the first argument is treated as a format string with %s placeholders, and subsequent arguments fill those placeholders. Since your first f-string has no placeholders, the second f-string (f"lat={self.latitude}, \n lng={self.longitude}") is never included in the log output.

Additionally, the static analysis tool is flagging G004 (logging statement uses f-string), which this fix would also resolve.

,

🐛 Suggested fix using lazy formatting
             else:
-                logger.debug(
-                    f"Skipping session {self.id} due to invalid coordinates:",
-                    f"lat={self.latitude}, \n lng={self.longitude}",
-                )
+                logger.debug(
+                    "Skipping session %s due to invalid coordinates: lat=%s, lng=%s",
+                    self.id, self.latitude, self.longitude,
+                )
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@web/models.py` around lines 494 - 497, The logger.debug call currently passes
two f-strings so the second is discarded and triggers G004; change the call in
the class where logger.debug is invoked (referencing self.id, self.latitude,
self.longitude) to use a single format string with lazy logging placeholders and
pass the id/latitude/longitude as separate arguments (e.g. one format string
describing the session id and coordinates and then the three values), ensuring
the full message is logged and avoiding f-strings in the logging call.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@web/models.py`:
- Around line 494-497: The logger.debug call currently passes two f-strings so
the second is discarded and triggers G004; change the call in the class where
logger.debug is invoked (referencing self.id, self.latitude, self.longitude) to
use a single format string with lazy logging placeholders and pass the
id/latitude/longitude as separate arguments (e.g. one format string describing
the session id and coordinates and then the three values), ensuring the full
message is logged and avoiding f-strings in the logging call.

ℹ️ Review info
⚙️ Run configuration

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

Review profile: ASSERTIVE

Plan: Pro

Run ID: 637f6806-2376-47b9-a781-39e368435ee8

📥 Commits

Reviewing files that changed from the base of the PR and between 698460d and c3b8645.

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

@Diegomed11
Copy link
Author

Fixed in the latest commit: switched to logger.exception() in all except blocks for automatic traceback capture.

@github-actions github-actions bot dismissed their stale review March 21, 2026 15:45

All review conversations have been resolved.

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

🤖 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/views.py`:
- Line 3257: The warning-level log of validation failures should be lowered to
debug to avoid noisy logs; change the logger.warning("Form errors: %s",
form.errors) call in this view to logger.debug("Form errors: %s", form.errors)
(or gate it behind a debug/config flag) so validation errors (from the form
variable) are recorded at debug level rather than warning.
- Line 1: The stdlib import "import logging" is out of isort order; update the
import block in web/views.py so standard library imports are sorted per isort
Black profile (or run isort --profile=black) ensuring "import logging" is placed
in the correct stdlib group and reorder surrounding imports accordingly; re-run
linters to confirm the import order passes.

ℹ️ Review info
⚙️ Run configuration

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

Review profile: ASSERTIVE

Plan: Pro

Run ID: 9ea30885-3b68-4f09-9980-fffd9f27eab8

📥 Commits

Reviewing files that changed from the base of the PR and between c3b8645 and 4912a73.

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

@Diegomed11
Copy link
Author

@A1L13N ready for review. Completes logging cleanup across models.py, quiz_views.py, and views.py. All feedback addressed.

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

Labels

files-changed: 3 PR changes 3 files

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant