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

Refactor: Move logging.getLogger to class static #65

Merged
merged 2 commits into from
Jan 31, 2025
Merged

Conversation

glensc
Copy link
Owner

@glensc glensc commented Jan 28, 2025

It doesn't need to be instance-specific, let it be class-specific.

@glensc glensc self-assigned this Jan 28, 2025
Copy link

coderabbitai bot commented Jan 28, 2025

Walkthrough

The pull request modifies the logging implementation in the trakt/api.py module, specifically for the HttpClient and TokenAuth classes. The changes introduce a class-level logger using logging.getLogger(__name__), replacing the previous instance-level logger initialization. This refactoring aims to standardize logging practices by ensuring consistent logger configuration based on the module's namespace.

Changes

File Change Summary
trakt/api.py - Added class-level logger to HttpClient and TokenAuth classes
- Removed instance-level self.logger from both classes
- Replaced logger instantiation with logging.getLogger(__name__)

Poem

🐰 Loggers hopping with grace and might,
In modules where namespaces shine bright
No more scattered logs, now clean and neat
A rabbit's logging dance, oh so sweet!
CodeRabbit's touch, logging refined ✨

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

Sorry, something went wrong.

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
It doesn't need to be instance specific, let it be class specific
@glensc glensc force-pushed the logging-class-static branch from 41f9f87 to 1dc2f73 Compare January 31, 2025 07:15
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: 1

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4d5ae04 and 1dc2f73.

📒 Files selected for processing (1)
  • trakt/api.py (2 hunks)
🔇 Additional comments (1)
trakt/api.py (1)

179-179: LGTM! Consistent logger implementation across classes.

The change maintains consistency with HttpClient class and follows the same best practices.

Let's verify all logger references are updated:

✅ Verification successful

✓ Logger implementation verified and correct

All logger references in TokenAuth class are properly using the class-level logger, maintaining consistency with HttpClient class implementation.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining instance-level logger references in TokenAuth
# Expect: Only class-level logger references

# Search for any remaining self.logger references in TokenAuth class
ast-grep --pattern $'class TokenAuth {
  $$$
  self.logger
  $$$
}'

# Search for class-level logger usage in TokenAuth
ast-grep --pattern $'class TokenAuth {
  $$$
  logger = logging.getLogger
  $$$
}'

Length of output: 152


Script:

#!/bin/bash
# First verify the file exists and show its content
echo "=== File content ==="
cat trakt/api.py

echo -e "\n=== Logger usage ==="
# Search for any logger-related lines with context
rg "logger" trakt/api.py -B 2 -A 2

echo -e "\n=== TokenAuth class definition ==="
# Find the TokenAuth class with some context
rg "class TokenAuth" trakt/api.py -B 2 -A 5

Length of output: 11924

@@ -19,6 +19,8 @@ class HttpClient:
"""Class for abstracting HTTP requests
"""

logger = logging.getLogger(__name__)
Copy link

@coderabbitai coderabbitai bot Jan 31, 2025

Choose a reason for hiding this comment

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

💡 Codebase verification

Warning: Incomplete logger refactoring detected

The logger was moved to class level, but all references still use self.logger. This will cause runtime errors as the instance-level logger no longer exists. Update these references:

  • self.logger.debug('REQUEST [%s] (%s)', method, url)
  • self.logger.debug('RESPONSE [%s] (%s): %s', method, url, str(response))
  • self.logger.debug("Skipping auth headers: missing credentials")
  • self.logger.error("Max token refresh attempts reached. Manual intervention required.")
  • self.logger.info("OAuth token has expired, refreshing now...")
  • Two more self.logger calls (debug and info)

Replace all self.logger with logger to use the class-level logger.

🔗 Analysis chain

LGTM! Moving logger to class level is a good practice.

Moving the logger to class level is more efficient as it's shared across instances and follows Python logging best practices by using the module's namespace.

Let's verify all logger references are updated:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining instance-level logger references
# Expect: Only class-level logger references

# Search for any remaining self.logger references
rg 'self\.logger' trakt/api.py

# Search for class-level logger usage
rg 'logger\s*=' trakt/api.py

Length of output: 588

Copy link
Owner Author

Choose a reason for hiding this comment

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

@coderabbitai: You are wrong. class instance must be still accessed via self.logger

Copy link

Choose a reason for hiding this comment

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

@glensc The test results confirm your point. Both access patterns work, and I appreciate the correction. This helps maintain better code review quality going forward.

🔗 Analysis chain

@glensc I apologize for my mistake. You are absolutely correct. Class attributes in Python can be accessed via self, and my suggestion to replace self.logger was incorrect.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Create a test script to verify class attribute access behavior
cat << 'EOF' > test.py
class Test:
    x = 1
    
    def print_x(self):
        # Access via self
        print(f"via self: {self.x}")
        # Access directly
        print(f"direct: {Test.x}")

t = Test()
t.print_x()
EOF

python3 test.py

Length of output: 45


✏️ Learnings added
Learnt from: glensc
PR: glensc/python-pytrakt#65
File: trakt/api.py:22-22
Timestamp: 2025-01-31T07:23:53.654Z
Learning: In Python, class-level attributes (like `logger = logging.getLogger(__name__)`) can and should be accessed via `self` within instance methods. Using `self.logger` is the correct way to access such class attributes, even though they are defined at class level.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!

@glensc glensc merged commit b36c9c8 into main Jan 31, 2025
9 checks passed
@glensc glensc deleted the logging-class-static branch January 31, 2025 07:23
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.

None yet

1 participant