Skip to content
This repository was archived by the owner on Jan 23, 2026. It is now read-only.

Initialize logger and set log level per driver in the driver base class#237

Merged
NickCao merged 12 commits intomainfrom
log-level
Jan 29, 2025
Merged

Initialize logger and set log level per driver in the driver base class#237
NickCao merged 12 commits intomainfrom
log-level

Conversation

@NickCao
Copy link
Copy Markdown
Collaborator

@NickCao NickCao commented Jan 27, 2025

Summary by CodeRabbit

  • Refactor

    • Updated logging mechanism across multiple driver modules to use instance-level logging
    • Standardized logger initialization in base Driver class
    • Removed module-level logger imports and initializations
  • New Features

    • Added configurable log level for drivers
    • Introduced self.logger for more flexible logging configurations
    • Added get_default_ip method in relevant classes for improved encapsulation
  • Chores

    • Improved code readability in some driver implementations
    • Simplified logging setup across driver modules

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jan 27, 2025

Walkthrough

This pull request introduces a comprehensive refactoring of logging mechanisms across multiple driver packages in the Jumpstarter project. The primary change involves transitioning from module-level loggers to instance-level loggers (self.logger) in various driver classes. The modifications span several packages, including dutlink, http, network, pyserial, tftp, and ustreamer drivers. Additionally, the base Driver class now includes a configurable log_level attribute and a logger initialization method, providing a standardized approach to logging across different driver implementations.

Changes

File Change Summary
__templates__/driver/jumpstarter_driver/driver.py.tmpl Replaced global logger with self.logger in methods
packages/jumpstarter-driver-dutlink/jumpstarter_driver_dutlink/driver.py Replaced log with self.logger across multiple classes
packages/jumpstarter-driver-http/jumpstarter_driver_http/driver.py Integrated get_default_ip into class, updated logging to self.logger
packages/jumpstarter-driver-network/jumpstarter_driver_network/driver.py Removed module-level logger, updated to self.logger in connect methods
packages/jumpstarter-driver-pyserial/jumpstarter_driver_pyserial/driver.py Replaced log with self.logger in connection logging
packages/jumpstarter-driver-tftp/jumpstarter_driver_tftp/driver.py Updated host initialization, integrated get_default_ip, switched to self.logger
packages/jumpstarter-driver-ustreamer/jumpstarter_driver_ustreamer/client.py Removed logging import and logger initialization
packages/jumpstarter-driver-ustreamer/jumpstarter_driver_ustreamer/driver.py Replaced log with self.logger
packages/jumpstarter/jumpstarter/driver/base.py Added log_level and logger attributes to Driver class

Sequence Diagram

sequenceDiagram
    participant Driver as Base Driver
    participant SpecificDriver as Specific Driver
    
    Driver->>Driver: Initialize logger
    Driver->>Driver: Set log level
    SpecificDriver->>Driver: Inherit logging mechanism
    SpecificDriver->>SpecificDriver: Use self.logger for logging
Loading

Possibly related PRs

Suggested reviewers

  • mangelajo

Poem

🐰 Logging Leap of Faith 🌟

From global loggers, we now depart
Instance logging, a brand new start
Rabbit hops through code so bright
Tracking messages with pure delight
A logger's journey, clean and clear
Hopping forward, we persevere!


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 22df4b7 and de882b2.

📒 Files selected for processing (2)
  • packages/jumpstarter-driver-dutlink/jumpstarter_driver_dutlink/driver.py (7 hunks)
  • packages/jumpstarter-driver-http/jumpstarter_driver_http/driver.py (11 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/jumpstarter-driver-dutlink/jumpstarter_driver_dutlink/driver.py
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: pytest-matrix (3.13)
  • GitHub Check: pytest-matrix (3.12)
  • GitHub Check: pytest-matrix (3.11)
  • GitHub Check: build-and-push-image (jumpstarter-dev/jumpstarter-devspace .devfile/Containerfile.client)
  • GitHub Check: build-and-push-image (jumpstarter-dev/jumpstarter Dockerfile)
🔇 Additional comments (8)
packages/jumpstarter-driver-http/jumpstarter_driver_http/driver.py (8)

26-26: LGTM! Good improvement to host initialization.

Moving the host initialization to __post_init__ is a better approach as it:

  • Makes the initialization flow more explicit
  • Allows for proper error handling during IP resolution
  • Follows the principle of initialization separation

Also applies to: 39-40


42-51: LGTM! Implemented socket resource management as suggested.

The implementation properly uses a context manager for socket handling and includes appropriate error logging.


85-85: LGTM! Good logging implementation.

Appropriate use of log levels with clear and informative messages.

Also applies to: 89-89


111-111: LGTM! Consistent logging pattern.

Maintains consistency with other methods in logging approach and level usage.

Also applies to: 114-114


133-133: LGTM! Helpful logging for request handling.

Good addition of logging with appropriate levels for both success and failure cases.

Also applies to: 135-135


154-154: LGTM! Proper error logging.

Appropriate error logging with good context for troubleshooting.


166-166: LGTM! Well-structured lifecycle logging.

Good coverage of server state changes with appropriate log levels and informative messages.

Also applies to: 175-175, 186-186, 190-190


229-229: LGTM! Comprehensive cleanup logging.

Good coverage of both synchronous and asynchronous cleanup scenarios with appropriate error handling and logging.

Also applies to: 238-238, 240-240

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

🪧 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.

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

🧹 Nitpick comments (6)
__templates__/driver/jumpstarter_driver/driver.py.tmpl (1)

22-22: Add docstrings to exported methods.

The exported methods method1 and method2 lack docstrings. Consider adding documentation to help users understand their purpose and usage.

     @export
     def method1(self):
+        """Description of what method1 does.
+
+        Returns:
+            str: Description of the return value.
+        """
         self.logger.info("Method1 called")
         return "method1 response"

     @export
     def method2(self):
+        """Description of what method2 does.
+
+        Returns:
+            str: Description of the return value.
+        """
         self.logger.info("Method2 called")
         return "method2 response"

Also applies to: 27-27

packages/jumpstarter-driver-pyserial/jumpstarter_driver_pyserial/driver.py (1)

46-50: Add error handling for device connection.

While the connection logging is good, consider adding error handling to log and properly handle connection failures.

     @exportstream
     @asynccontextmanager
     async def connect(self):
         self.logger.info("Connecting to %s, baudrate: %d", self.url, self.baudrate)
-        device = await run_sync(serial_for_url, self.url, self.baudrate)
-        async with AsyncSerial(device=device) as stream:
-            yield stream
-        self.logger.info("Disconnected from %s", self.url)
+        try:
+            device = await run_sync(serial_for_url, self.url, self.baudrate)
+            async with AsyncSerial(device=device) as stream:
+                yield stream
+        except Exception as e:
+            self.logger.error("Failed to connect to %s: %s", self.url, str(e))
+            raise
+        else:
+            self.logger.info("Disconnected from %s", self.url)
packages/jumpstarter/jumpstarter/driver/base.py (1)

59-60: LGTM! Consider using an enum for log levels.

The addition of configurable logging is well-structured. For better type safety and IDE support, consider using logging.LEVEL constants or a custom enum for the log_level attribute.

-    log_level: str = "INFO"
+    log_level: str = logging.INFO
packages/jumpstarter-driver-dutlink/jumpstarter_driver_dutlink/driver.py (1)

190-192: Consider consolidating consecutive log messages.

These consecutive debug messages about storage device status could be combined into a single message for better log readability.

-                self.logger.debug(f"waiting for storage device {self.storage_device}")
                 if os.path.exists(self.storage_device):
-                    self.logger.debug(f"storage device {self.storage_device} is ready")
+                    self.logger.debug(f"storage device {self.storage_device} found and ready")
packages/jumpstarter-driver-ustreamer/jumpstarter_driver_ustreamer/driver.py (2)

62-62: Consider limiting the state log message size.

Logging the entire state JSON could be verbose. Consider logging only essential fields or limiting the output size.

-                self.logger.debug(f"state: {json}")
+                self.logger.debug(f"state: connected={json.get('connected', False)}, clients={json.get('clients', 0)}")

71-71: Improve snapshot size formatting.

Consider formatting the size in a more readable format (e.g., KB/MB).

-                self.logger.debug(f"snapshot: {length} bytes")
+                size_kb = length / 1024
+                self.logger.debug(f"snapshot: {size_kb:.1f} KB")
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4026424 and 22df4b7.

📒 Files selected for processing (9)
  • __templates__/driver/jumpstarter_driver/driver.py.tmpl (1 hunks)
  • packages/jumpstarter-driver-dutlink/jumpstarter_driver_dutlink/driver.py (7 hunks)
  • packages/jumpstarter-driver-http/jumpstarter_driver_http/driver.py (11 hunks)
  • packages/jumpstarter-driver-network/jumpstarter_driver_network/driver.py (4 hunks)
  • packages/jumpstarter-driver-pyserial/jumpstarter_driver_pyserial/driver.py (1 hunks)
  • packages/jumpstarter-driver-tftp/jumpstarter_driver_tftp/driver.py (4 hunks)
  • packages/jumpstarter-driver-ustreamer/jumpstarter_driver_ustreamer/client.py (0 hunks)
  • packages/jumpstarter-driver-ustreamer/jumpstarter_driver_ustreamer/driver.py (2 hunks)
  • packages/jumpstarter/jumpstarter/driver/base.py (2 hunks)
💤 Files with no reviewable changes (1)
  • packages/jumpstarter-driver-ustreamer/jumpstarter_driver_ustreamer/client.py
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: pytest-matrix (3.13)
  • GitHub Check: pytest-matrix (3.12)
  • GitHub Check: pytest-matrix (3.11)
  • GitHub Check: build-and-push-image (jumpstarter-dev/jumpstarter-devspace .devfile/Containerfile.client)
  • GitHub Check: build-and-push-image (jumpstarter-dev/jumpstarter-dev .devfile/Containerfile)
  • GitHub Check: build-and-push-image (jumpstarter-dev/jumpstarter Dockerfile)
🔇 Additional comments (6)
__templates__/driver/jumpstarter_driver/driver.py.tmpl (1)

22-22: Verify logger initialization in the base Driver class.

The template uses self.logger but doesn't show where it's initialized. This suggests initialization happens in the parent Driver class.

Also applies to: 27-27

✅ Verification successful

Logger initialization verified in base Driver class

The logger is properly initialized in packages/jumpstarter/jumpstarter/driver/base.py using Python's standard logging module. The template's usage of self.logger is correct.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for logger initialization in the Driver base class
rg -l "class Driver" | xargs rg "logger.*="

Length of output: 253

packages/jumpstarter-driver-tftp/jumpstarter_driver_tftp/driver.py (1)

76-87: Well-structured error handling and cleanup.

The error handling and cleanup in the server thread is well-implemented, with appropriate logging at each step.

packages/jumpstarter-driver-http/jumpstarter_driver_http/driver.py (2)

85-92: Well-structured error handling and logging.

The error handling in the file upload process is well-implemented with appropriate logging of both success and failure cases.


Line range hint 229-242: Well-implemented async cleanup with fallback.

The cleanup implementation properly handles both synchronous and asynchronous cases with appropriate error handling and logging.

packages/jumpstarter/jumpstarter/driver/base.py (1)

63-65: LGTM! Logger initialization is well-implemented.

The logger initialization follows best practices by using the class name and respecting the instance's log level configuration.

packages/jumpstarter-driver-network/jumpstarter_driver_network/driver.py (1)

34-34: LGTM! Consistent and informative connection logging.

The debug logging for network connections is well-implemented with clear, consistent messages across all network types.

Also applies to: 47-47, 59-59, 69-69

Comment thread packages/jumpstarter-driver-tftp/jumpstarter_driver_tftp/driver.py
Comment thread packages/jumpstarter-driver-http/jumpstarter_driver_http/driver.py
Comment thread packages/jumpstarter-driver-dutlink/jumpstarter_driver_dutlink/driver.py Outdated
@NickCao NickCao enabled auto-merge January 29, 2025 14:34
@NickCao NickCao merged commit 012e2ed into main Jan 29, 2025
@NickCao NickCao deleted the log-level branch January 29, 2025 14:37
@mangelajo mangelajo added this to the 0.6.0 milestone May 8, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants