Skip to content

Support -o log_cli=<true/false> to turn off console logging#884

Merged
dbasunag merged 5 commits intoopendatahub-io:mainfrom
dbasunag:log_cli_support
Dec 1, 2025
Merged

Support -o log_cli=<true/false> to turn off console logging#884
dbasunag merged 5 commits intoopendatahub-io:mainfrom
dbasunag:log_cli_support

Conversation

@dbasunag
Copy link
Copy Markdown
Collaborator

@dbasunag dbasunag commented Nov 26, 2025

Description

How Has This Been Tested?

Merge criteria:

  • The commits are squashed in a cohesive manner and have meaningful messages.
  • Testing instructions have been added in the PR body (for PRs involving changes that are not immediately obvious).
  • The developer has manually tested the changes and verified that the changes work

Summary by CodeRabbit

  • New Features

    • Console logging can be toggled on/off (respects CLI overrides) and log level can be provided as a string.
  • Improvements

    • Logging is initialized earlier to ensure consistent startup logs and a cleaner log file before runs.
    • Console handler is optional; file logging remains enabled. Must-gather collection behavior preserved with updated logging sequence.
  • Documentation

    • Added guidance for turning off console logging.

✏️ Tip: You can customize this high-level summary in your review settings.

@dbasunag dbasunag requested a review from a team as a code owner November 26, 2025 21:08
@github-actions
Copy link
Copy Markdown

The following are automatically added/executed:

  • PR size label.
  • Run pre-commit
  • Run tox
  • Add PR author as the PR assignee
  • Build image based on the PR

Available user actions:

  • To mark a PR as WIP, add /wip in a comment. To remove it from the PR comment /wip cancel to the PR.
  • To block merging of a PR, add /hold in a comment. To un-block merging of PR comment /hold cancel.
  • To mark a PR as approved, add /lgtm in a comment. To remove, add /lgtm cancel.
    lgtm label removed on each new commit push.
  • To mark PR as verified comment /verified to the PR, to un-verify comment /verified cancel to the PR.
    verified label removed on each new commit push.
  • To Cherry-pick a merged PR /cherry-pick <target_branch_name> to the PR. If <target_branch_name> is valid,
    and the current PR is merged, a cherry-picked PR would be created and linked to the current PR.
  • To build and push image to quay, add /build-push-pr-image in a comment. This would create an image with tag
    pr-<pr_number> to quay repository. This image tag, however would be deleted on PR merge or close action.
Supported labels

{'/build-push-pr-image', '/verified', '/hold', '/wip', '/cherry-pick', '/lgtm'}

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Nov 26, 2025

📝 Walkthrough

Walkthrough

Restructures test logging initialization: logging is configured earlier with resolved log_cli level and optional console output, existing test log file is removed before setup, and must_gather initialization runs after logging is established; docs add instructions to disable console logging.

Changes

Cohort / File(s) Summary
Test configuration: conftest
conftest.py
Resolves log_file by name, normalizes log_cli_level strings to numeric levels, detects -o log_cli overrides to set enable_console, removes existing log file before configuring logging, configures logging earlier, defers the log-path write until after setup, and retains must_gather initialization/cleanup with updated sequencing.
Logging utility
utilities/logger.py
setup_logging signature extended with enable_console: bool = True; accepts string or int log_level (normalizes string names), conditionally creates and attaches a console handler only when enable_console is True, always configures file handler, composes handlers dynamically for QueueListener, and rebinds root/named loggers to the queue-based system.
Documentation
docs/GETTING_STARTED.md
Adds a "Turning off console logging" subsection showing how to disable pytest console logging (e.g., -o log_cli=false); content appears inserted in two places (duplicate).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20–30 minutes

  • Verify string-to-int log level normalization handles invalid names and fallback behavior.
  • Confirm detection of -o log_cli override correctly sets enable_console and interacts with any PYTEST_DISABLE_CONSOLE_LOG behavior.
  • Review QueueListener handler composition and shutdown paths when console handler is omitted.
  • Ensure ordering: no log writes occur before logging is configured and must_gather initialization occurs after setup.
  • Remove duplicated doc insertion or confirm intended duplication.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ 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 clearly and specifically describes the main change: adding support for the -o log_cli option to control console logging behavior. It directly corresponds to the primary functionality added across conftest.py, utilities/logger.py, and documentation.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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

🧹 Nitpick comments (2)
utilities/logger.py (2)

25-27: Update docstring for new parameter.

The function signature now accepts enable_console but the docstring doesn't document it. Additionally, lines 75-77 suggest log_level can be a string, but the docstring says it's an int.

Apply this diff to update the docstring:

 def setup_logging(
     log_level: int, log_file: str = "/tmp/pytest-tests.log", thread_name: str | None = None, enable_console: bool = True
 ) -> QueueListener:
     """
     Setup basic/root logging using QueueHandler/QueueListener
     to consolidate log messages into a single stream to be written to multiple outputs.
 
     Args:
-        log_level (int): log level
+        log_level (int | str): log level (int constant or string name like 'INFO')
         log_file (str): logging output file
         thread_name (str | None): optional thread_name id prefix, e.g., [gw0]
+        enable_console (bool): whether to enable console logging (default: True)
 
     Returns:
         QueueListener: Process monitoring the log Queue

70-72: Document the PYTEST_DISABLE_CONSOLE_LOG environment variable.

This environment variable provides an alternative way to disable console logging but isn't mentioned in the docstring or any user-facing documentation in this PR.

Consider adding a note to the docstring about this environment override.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4c8b808 and 74a540c.

📒 Files selected for processing (2)
  • conftest.py (1 hunks)
  • utilities/logger.py (4 hunks)
🧰 Additional context used
🪛 Ruff (0.14.5)
utilities/logger.py

26-26: Probable insecure usage of temporary file or directory: "/tmp/pytest-tests.log"

(S108)

conftest.py

311-311: Do not catch blind exception: Exception

(BLE001)


313-313: Use logging.exception instead of logging.error

Replace with exception

(TRY400)

🔇 Additional comments (6)
conftest.py (4)

284-293: LGTM! Clean log level conversion.

The string-to-int log level conversion is correctly implemented with appropriate fallback to logging.INFO.


295-297: LGTM! Proper cleanup sequence.

Removing the old log file before initializing logging is the correct approach.


317-322: LGTM! Proper logging initialization.

The setup_logging call correctly passes all computed parameters.


324-328: LGTM! Post-configuration logging is safe.

Logging after setup_logging completes is the correct approach, as noted by the comment.

utilities/logger.py (2)

83-84: LGTM! Dynamic handler composition.

Using *handlers to unpack the dynamic handler list is the right approach for conditional console logging.


108-126: LGTM! Comprehensive logger reconfiguration.

The thorough clearing and reconfiguration of all loggers ensures consistent queue-based logging behavior. The redundant handler clearing (lines 118 and 123-125) is defensive but harmless.

Comment thread conftest.py
Comment thread utilities/logger.py
Copy link
Copy Markdown
Contributor

@jgarciao jgarciao left a comment

Choose a reason for hiding this comment

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

Could you add a note in GETTING_STARTED.md explaining how to use this parameter?

Comment thread conftest.py
Comment thread utilities/logger.py Outdated
Comment thread utilities/logger.py Outdated
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

♻️ Duplicate comments (1)
utilities/logger.py (1)

64-72: Move log_level normalization before any setLevel calls (still applied too late).

log_file_handler.setLevel(level=log_level) on Line 65 can still receive a lowercase string (e.g. "debug"), while you only normalize/uppercase log_level afterwards (Lines 69‑71). In that case, Handler.setLevel will raise ValueError("Unknown level") before your normalization runs.

This is the same issue noted in the earlier review; the conversion needs to happen once, up front, before any handler/logger setLevel calls.

Suggested change:

  1. Add normalization near the top of setup_logging (before any setLevel usage), e.g.:
    # Normalize log_level to an int once, early
    if isinstance(log_level, str):
        log_level = getattr(logging, log_level.upper(), logging.INFO)
  1. Remove the late conversion in this block:
-    # Convert log_level to int if it's a string
-    if isinstance(log_level, str):
-        log_level = getattr(logging, log_level.upper(), logging.INFO)

This way all handlers/loggers consistently see a valid integer level and lowercase strings work as intended.

🧹 Nitpick comments (4)
utilities/logger.py (4)

5-5: Tighten type hints for handlers instead of using Any.

handlers is always a list of logging handlers, so Any is broader than needed. You can keep the code self-documenting without extra imports:

-from typing import Optional, Any
+from typing import Optional
@@
-    handlers: list[Any] = [log_file_handler]
+    handlers: list[logging.Handler] = [log_file_handler]

This avoids Any while reflecting the actual type.

Also applies to: 67-67


24-37: Align setup_logging signature and docstring with actual behavior (log_level + enable_console).

Two small consistency issues here:

  • log_level is annotated and documented as int, but the function explicitly accepts strings and normalizes them later.
  • The new enable_console parameter isn’t documented in the Args section.

Consider updating both signature and docstring, e.g.:

def setup_logging(
    log_level: int | str,
    log_file: str = "/tmp/pytest-tests.log",
    thread_name: str | None = None,
    enable_console: bool = True,
) -> QueueListener:
    """
    Args:
        log_level (int | str): Log level (e.g. logging.INFO or "info"/"INFO").
        log_file (str): Logging output file.
        thread_name (str | None): Optional thread_name id prefix, e.g., [gw0].
        enable_console (bool): Whether to attach a console (stream) handler.
    """

25-25: Reconsider hard‑coding /tmp/pytest-tests.log as the default log file.

Ruff’s S108 warning is about potential issues with world‑writable temp dirs. Even if this is “just tests”, you might want a slightly safer/more flexible default, e.g.:

  • Use tempfile.gettempdir() or Path(tempfile.gettempdir()) / "pytest-tests.log".
  • Or default to a repository‑local path and make /tmp opt‑in via config/ENV.

Not urgent, but worth a follow‑up if these logs can contain sensitive data or run on shared hosts.


103-121: Central re‑binding of all loggers to the queue handler may override third‑party logging configs.

The new block:

  • Iterates over logging.root.manager.loggerDict and clears/rewires every logger (except "root" and "basic") to root_log_queue_handler with propagate = False.
  • Resets logging.root to only use root_log_queue_handler.

This guarantees everything flows through your queue + console/file policy, which is nice for tests, but it also:

  • Discards any handlers/filters third‑party libraries may have attached.
  • Changes propagate semantics for existing loggers.

If that’s intentional for this test harness, document it clearly where setup_logging is called; otherwise, you may want a narrower scope (e.g., only re‑bind known logger namespaces, or skip loggers that already use your queue handler). Also note Lines 117‑120 are effectively redundant right after handlers.clear() + single addHandler, so they can be trimmed.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2ebc577 and f5e520a.

📒 Files selected for processing (1)
  • utilities/logger.py (4 hunks)
🧰 Additional context used
🪛 Ruff (0.14.6)
utilities/logger.py

25-25: Probable insecure usage of temporary file or directory: "/tmp/pytest-tests.log"

(S108)

🔇 Additional comments (1)
utilities/logger.py (1)

73-76: Console toggle via enable_console is straightforward and matches the PR goal.

Conditionally creating the StreamHandler and wiring it into the QueueListener based solely on enable_console gives a clear, single control point for console logging. This aligns well with the -o log_cli=<true/false> behavior described in the PR.

@dbasunag dbasunag merged commit ae6dec0 into opendatahub-io:main Dec 1, 2025
8 checks passed
@dbasunag dbasunag deleted the log_cli_support branch December 1, 2025 15:18
@github-actions
Copy link
Copy Markdown

github-actions bot commented Dec 1, 2025

Status of building tag latest: success.
Status of pushing tag latest to image registry: success.

mwaykole pushed a commit to mwaykole/opendatahub-tests that referenced this pull request Jan 23, 2026
…hub-io#884)

* Support -o log_cli=<true/false> to turn off console logging

* Add information on how to disable console logging

* Removed support for PYTEST_DISABLE_CONSOLE_LOG as not necessary
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants