Skip to content

Refactor: Migrate from print statements to Python's logging module#4

Merged
tutunak merged 3 commits intomasterfrom
migrate-to-logging
May 29, 2025
Merged

Refactor: Migrate from print statements to Python's logging module#4
tutunak merged 3 commits intomasterfrom
migrate-to-logging

Conversation

@tutunak
Copy link
Copy Markdown
Owner

@tutunak tutunak commented May 29, 2025

This commit replaces all instances of print() with calls to Python's standard logging module.

Key changes:

  • Configured a logger in sbg.py with a standard format and INFO level.
  • Replaced informational, warning, and error print() calls with logger.info(), logger.warning(), and logger.error() respectively.
  • Handled sys.exit() calls to log critical errors or informational messages (like user abortion) before exiting.
  • Updated unit tests in test_sbg.py to use self.assertLogs for capturing and verifying log output, ensuring continued test coverage.
  • Added a note to README.md about the use of the logging module.

This change provides more structured and configurable logging, allowing you to control log verbosity and output destinations (e.g., file output) if needed in the future.

Summary by CodeRabbit

  • Documentation

    • Added a "Logging" section to the README, explaining how console output is managed and how users can control logging behavior.
  • Refactor

    • Replaced all direct print statements with standardized logging for informational, warning, and error messages.
    • Updated error handling to use logging for user aborts and fatal exceptions.
  • Tests

    • Updated tests to use logging capture instead of manual output redirection for verifying warning and error messages.

This commit replaces all instances of `print()` with calls to Python's
standard `logging` module.

Key changes:
- Configured a logger in `sbg.py` with a standard format and INFO level.
- Replaced informational, warning, and error `print()` calls with
  `logger.info()`, `logger.warning()`, and `logger.error()` respectively.
- Handled `sys.exit()` calls to log critical errors or informational
  messages (like user abortion) before exiting.
- Updated unit tests in `test_sbg.py` to use `self.assertLogs` for
  capturing and verifying log output, ensuring continued test coverage.
- Added a note to `README.md` about the use of the logging module.

This change provides more structured and configurable logging, allowing
you to control log verbosity and output destinations (e.g., file output)
if needed in the future.
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented May 29, 2025

Warning

Rate limit exceeded

@tutunak has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 25 minutes and 51 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.

📥 Commits

Reviewing files that changed from the base of the PR and between 8a768fa and 90c67d0.

📒 Files selected for processing (1)
  • sbg.py (5 hunks)

Walkthrough

The changes introduce standardized logging throughout the codebase by replacing all direct print statements with Python's logging module. The README is updated to document this logging approach. Test cases are refactored to capture and assert log messages using unittest's assertLogs, replacing manual stdout redirection.

Changes

File(s) Change Summary
README.md Added a section describing the new logging approach using Python's logging module.
sbg.py Replaced print statements with logging calls; initialized logger and logging configuration.
test_sbg.py Updated tests to use assertLogs for capturing and asserting log messages instead of stdout hacks.

Poem

🐇
Logs now hop where prints once lay,
Messages tidy, in a logging array.
Errors and warnings, with levels so neat,
Captured in tests, a bunny’s small feat.
The console is calm, the output pristine—
A rabbit’s delight, so clear and serene!

✨ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in 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.

This commit updates logger calls in `sbg.py` to use %-formatting
with positional arguments (e.g., `logger.info("Message: %s", arg)`)
instead of f-strings.

This change adheres to logging best practices, as it avoids unnecessary
string formatting if the log message's level is not high enough to be
emitted.

Unit tests in `test_sbg.py` have been confirmed to pass with these
changes, as the final log output remains the same.
coderabbitai bot added a commit that referenced this pull request May 29, 2025
Docstrings generation was requested by @tutunak.

* #4 (comment)

The following files were modified:

* `sbg.py`
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented May 29, 2025

Note

Generated docstrings for this pull request at #5

Copy link
Copy Markdown
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: 0

🧹 Nitpick comments (1)
sbg.py (1)

98-98: Consider the impact of force=True on library usage

The force=True parameter will override any existing logging configuration, which could be problematic if this script is ever imported as a module by other applications.

Consider making the logging configuration conditional or allow it to be disabled:

-    logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', force=True)
+    if not logging.getLogger().handlers:
+        logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

Alternatively, you could add a parameter to control logging configuration for better modularity.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 80bc3d2 and 8a768fa.

📒 Files selected for processing (3)
  • README.md (1 hunks)
  • sbg.py (4 hunks)
  • test_sbg.py (4 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
test_sbg.py (1)
sbg.py (2)
  • gather_all_projects (61-79)
  • clone_or_pull (82-95)
🔇 Additional comments (11)
sbg.py (6)

6-6: LGTM: Proper logging setup

The logging import and logger initialization follow Python best practices by using __name__ for the logger name, which creates a hierarchical logger namespace.

Also applies to: 9-9


74-74: LGTM: Appropriate warning level for HTTP errors

Using logger.warning() for HTTP errors during group fetching is appropriate, as these are non-fatal issues that the user should be aware of but don't stop the overall process.


85-85: LGTM: Appropriate info level for operational messages

Using logger.info() for clone/pull operations provides good visibility into the script's progress without being overly verbose.

Also applies to: 91-91


89-89: LGTM: Appropriate error level for subprocess failures

Using logger.error() for git command failures is correct, as these are actual errors that prevent successful operation on specific repositories.

Also applies to: 95-95


105-105: LGTM: Good progress reporting

The informational logging provides clear feedback about the script's progress, including group processing and total project counts.

Also applies to: 108-108


133-137: LGTM: Proper exception handling with appropriate logging

The exception handling correctly uses:

  • logger.info() for user interruption (not an error)
  • logger.critical() for fatal exceptions
  • Appropriate exit codes (0 for user abort, 1 for fatal errors)

This maintains the same behavior as before while providing structured logging.

test_sbg.py (4)

9-9: LGTM: Proper import for logging in tests

Adding the logging import is necessary for the test updates to capture and assert on log messages.


43-44: LGTM: Proper logging configuration for tests

Setting the logger level to INFO ensures that log messages will be captured by assertLogs. The comment clearly explains the purpose of this configuration.


137-142: LGTM: Proper migration to assertLogs for warning capture

The test correctly:

  • Uses assertLogs with the specific logger and WARNING level
  • Maintains the same assertion logic by checking for the expected warning message
  • Verifies both the functional behavior (2 projects returned) and the logging behavior

This properly tests the new logging implementation while maintaining test coverage.


172-175: LGTM: Proper migration to assertLogs for error capture

The test correctly captures ERROR level logs and verifies the expected error message content. The assertion properly checks that the clone failure message is logged.

README.md (1)

112-116: LGTM: Clear and helpful logging documentation

The new "Logging" section effectively:

  • Explains the adoption of Python's logging module
  • Highlights the benefits of structured logging (verbosity control, output destinations)
  • Clearly states the default behavior (INFO level to stdout)
  • Provides users with useful information about the logging approach

This documentation aligns well with the implementation changes and helps users understand the new logging behavior.

Docstrings generation was requested by @tutunak.

* #4 (comment)

The following files were modified:

* `sbg.py`
@tutunak tutunak merged commit 7044f78 into master May 29, 2025
8 checks passed
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