Skip to content

Use RichHandler and remove existing log handler when init log - #693

Merged
aantn merged 2 commits into
masterfrom
remove-existing-log-handler
Jul 23, 2025
Merged

aantn merged 2 commits into
masterfrom
remove-existing-log-handler

Conversation

@mainred

@mainred mainred commented Jul 23, 2025 •

Copy link
Copy Markdown
Collaborator

When importing holmes and leverage RichHandler to handle log, we need to remove existing log handlers to not let existing log handler break the outpout format of holmes CLI.

As a result, the log may not be printed out as expected, for example,

Welcome to HolmesGPT: Type '/exit' to exit, '/help' for commands.
User: what's my cluster info

Thinking...

╭─ AI Response ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│                                                                                                                                                       │
│  Cluster: AKS, region southeastasia, 7 nodes.                                                                                                         │
│                                                                                                                                                       │
│   • Nodepools: containerd2 (Azure Linux), nodepool1 (Ubuntu), win (Windows)                                                                           │
│   • Kubernetes version: v1.33.0                                                                                                                       │
│   • Network policy: calico                                                                                                                            │
│   • All nodes Ready, VMSS-backed, Premium_LRS storage.                                                                                                │
│                                                                                                                                                       │
╰───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯

User:

The force arg is explained here:

    force     If this keyword  is specified as true, any existing handlers
              attached to the root logger are removed and closed, before
              carrying out the configuration as specified by the other
              arguments.

https://github.com/python/cpython/blob/e41c1ce585827f92dab9b7a7fc3df2bda2f817fe/Lib/logging/__init__.py#L2038-L2041

After the change:

✅ Toolset kubernetes/live-metrics
✅ Toolset kubernetes/kube-prometheus-stack
✅ Toolset internet
✅ Toolset runbook
✅ Toolset kubernetes/logs
✅ Toolset docker/core
✅ Toolset helm/core
✅ Toolset kubernetes/core
discovered service with label-selector: `app=kube-prometheus-stack-prometheus` at url:
`http://prometheus-kube-prometheus-prometheus.default.svc.cluster.local:9090`
Prometheus auto discovered at url http://prometheus-kube-prometheus-prometheus.default.svc.cluster.local:9090
❌ Toolset prometheus/metrics: Failed to initialize using url=http://prometheus-kube-prometheus-prometheus.default.svc.cluster.local:9090/-/healthy
Using 36 datasources (toolsets). To refresh: `holmes toolset refresh`
Welcome to HolmesGPT: Type '/exit' to exit, '/help' for commands.
User: what's my cluster info

Thinking...

Running tool #1 kubectl_get_by_kind_in_cluster: kubectl get -A --show-labels -o wide node
  Finished #1 in 0.94s, output length: 10,264 characters - /show to view contents

╭─ AI Response ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│                                                                                                                                                       │
│  Cluster: MC_qinhao_credential-provider-win_southeastasia Region: southeastasia Kubernetes version: v1.33.0 Nodes: 7 (6 Linux, 1 Windows) Nodepools:  │
│  containerd2 (Azure Linux), nodepool1 (Ubuntu), win (Windows) Network policy: calico VM type: Standard_DS2_v2 (Linux), Standard_D2ls_v5 (Windows)     │
│  All nodes Ready.                                                                                                                                     │
│                                                                                                                                                       │
╰───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯

@coderabbitai

coderabbitai Bot commented Jul 23, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

The change updates the init_logging function in holmes/utils/console/logging.py by adding the force=True argument to all logging.basicConfig calls for different verbosity levels. No other logic or configuration changes were introduced.

Changes

File(s) Change Summary
holmes/utils/console/logging.py Added force=True to all logging.basicConfig calls in init_logging

Estimated code review effort

1 (~2 minutes)


📜 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 74890c937d330d163f0d91a742df1e84ce3c3a85 and d043457.

📒 Files selected for processing (1)
  • holmes/utils/console/logging.py (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • holmes/utils/console/logging.py
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (7)
  • GitHub Check: build (3.12)
  • GitHub Check: build (3.11)
  • GitHub Check: build (3.10)
  • GitHub Check: build (3.12)
  • GitHub Check: build (3.11)
  • GitHub Check: build (3.10)
  • GitHub Check: llm_evals
✨ 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.

@mainred mainred changed the title remove existing log handler Use RichHandler and remove existing log handler when init log Jul 23, 2025

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🔭 Outside diff range comments (1)
holmes/utils/console/logging.py (1)

48-61: force=True belongs to logging.basicConfig, not RichHandler

RichHandler does not accept a force kw-arg (see rich.logging.RichHandler signature).
Placing it here raises a TypeError at runtime and is already flagged by mypy.
The force flag should be passed to logging.basicConfig, which is exactly what the PR intends—removing pre-existing handlers.

Proposed patch (apply to all three basicConfig blocks):

-        logging.basicConfig(
-            level=logging.DEBUG,           # or INFO in the other blocks
-            format="%(message)s",
-            handlers=[
-                RichHandler(
-                    force=True,             # ❌ wrong place
-                    show_level=False,
+        logging.basicConfig(
+            level=logging.DEBUG,           # or INFO in the other blocks
+            format="%(message)s",
+            force=True,                    # ✅ correct place
+            handlers=[
+                RichHandler(
+                    show_level=False,

Repeat the same change for the VERBOSE and NORMAL branches (lines 63-76 and 80-93).

This will satisfy mypy and prevent runtime crashes while still wiping existing handlers.
Python ≥ 3.8 is required for force=True; ensure CI/runtime image meets that.

Also applies to: 63-76, 80-93

🧹 Nitpick comments (1)
holmes/utils/console/logging.py (1)

44-96: Consider DRYing the logging configuration

The three branches differ only in level and the post-config tweaks. Duplicating the whole basicConfig block invites drift.

Example refactor:

def _rich_basic(level: int) -> None:
    logging.basicConfig(
        level=level,
        format="%(message)s",
        force=True,
        handlers=[RichHandler(
            show_level=False,
            markup=True,
            show_time=False,
            show_path=False,
            console=Console(width=None),
        )],
    )

# usage
if verbosity == Verbosity.VERY_VERBOSE:
    _rich_basic(logging.DEBUG)
elif verbosity == Verbosity.VERBOSE:
    _rich_basic(logging.INFO)
    logging.getLogger().setLevel(logging.DEBUG)
    suppress_noisy_logs()
else:
    _rich_basic(logging.INFO)
    suppress_noisy_logs()

Reduces duplication and centralises handler options.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between be51687 and 74890c937d330d163f0d91a742df1e84ce3c3a85.

📒 Files selected for processing (1)
  • holmes/utils/console/logging.py (3 hunks)
🪛 GitHub Actions: Build and test HolmesGPT
holmes/utils/console/logging.py

[error] 52-52: mypy: Unexpected keyword argument "force" for "RichHandler" (call-arg)


[error] 67-67: mypy: Unexpected keyword argument "force" for "RichHandler" (call-arg)


[error] 84-84: mypy: Unexpected keyword argument "force" for "RichHandler" (call-arg)

🧰 Additional context used
🪛 GitHub Actions: Build and test HolmesGPT
holmes/utils/console/logging.py

[error] 52-52: mypy: Unexpected keyword argument "force" for "RichHandler" (call-arg)


[error] 67-67: mypy: Unexpected keyword argument "force" for "RichHandler" (call-arg)


[error] 84-84: mypy: Unexpected keyword argument "force" for "RichHandler" (call-arg)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Pre-commit checks
  • GitHub Check: llm_evals

@mainred
mainred force-pushed the remove-existing-log-handler branch from 74890c9 to d043457 Compare July 23, 2025 11:13
@mainred

mainred commented Jul 23, 2025

Copy link
Copy Markdown
Collaborator Author

@aantn this should has no impact on holmes which enforces RichHandler be the only log handler.

@aantn aantn left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM.

@aantn
aantn enabled auto-merge (squash) July 23, 2025 17:48
@github-actions

Copy link
Copy Markdown
Contributor

Results of HolmesGPT evals

  • ask_holmes: 21/72 test cases were successful, 0 regressions, 44 mock failures
  • investigate: 4/16 test cases were successful, 0 regressions, 11 mock failures
Test suite Test case Status
ask 01: how_many_pods ✅
ask 02: what_is_wrong_with_pod 🔧
ask 03: what_is_the_command_to_port_forward 🔧
ask 04: related_k8s_events 🔧
ask 05: image_version 🔧
ask 06: explain_issue 🔧
ask 07: high_latency 🔧
ask 08: sock_shop_frontend ⚠️
ask 09: crashpod 🔧
ask 10: image_pull_backoff 🔧
ask 11: init_containers 🔧
ask 12: job_crashing 🔧
ask 13: pending_node_selector 🔧
ask 14: pending_resources 🔧
ask 15: failed_readiness_probe 🔧
ask 16: failed_no_toolset_found ✅
ask 17: oom_kill 🔧
ask 18: crash_looping_v2 🔧
ask 19: detect_missing_app_details 🔧
ask 20: long_log_file_search ✅
ask 21: job_fail_curl_no_svc_account ⚠️
ask 22: high_latency_dbi_down 🔧
ask 23: app_error_in_current_logs 🔧
ask 24: misconfigured_pvc ✅
ask 25: misconfigured_ingress_class 🔧
ask 26: multi_container_logs 🔧
ask 27: permissions_error_no_helm_tools ✅
ask 28: permissions_error_helm_tools_enabled 🔧
ask 29: events_from_alert_manager 🔧
ask 30: basic_promql_graph_cluster_memory 🔧
ask 31: basic_promql_graph_pod_memory 🔧
ask 32: basic_promql_graph_pod_cpu 🔧
ask 33: http_latency_graph 🔧
ask 34: memory_graph 🔧
ask 35: tempo 🔧
ask 36: argocd_find_resource 🔧
ask 37: argocd_wrong_namespace 🔧
ask 38: rabbitmq_split_head 🔧
ask 39: failed_toolset ✅
ask 40: disabled_toolset ✅
ask 41: setup_argo ✅
ask 42: dns_issues_result_all_tools 🔧
ask 42: dns_issues_result_new_tools 🔧
ask 42: dns_issues_result_new_tools_no_runbook 🔧
ask 42: dns_issues_result_old_tools 🔧
ask 42: dns_issues_steps_new_all_tools 🔧
ask 42: dns_issues_steps_new_tools 🔧
ask 42: dns_issues_steps_old_tools 🔧
ask 43: current_datetime_from_prompt ✅
ask 43: slack_deployment_logs 🔧
ask 44: slack_statefulset_logs 🔧
ask 45: fetch_deployment_logs_simple ✅
ask 46: job_crashing_no_longer_exists 🔧
ask 47: truncated_logs_context_window ⚠️
ask 48: logs_since_thursday 🔧
ask 49: logs_since_last_week 🔧
ask 50: logs_since_specific_date 🔧
ask 51: logs_summarize_errors ✅
ask 52: logs_login_issues ⚠️
ask 53: logs_find_term ✅
ask 54: not_truncated_when_getting_pods ✅
ask 55: kafka_runbook 🔧
ask 56: kafka_runbook_no_tool ✅
ask 57: wrong_namespace ⚠️
ask 58: counting_pods_by_status ⚠️
ask 59: label_based_counting ✅
ask 60: time_based_filtering 🔧
ask 61: exact_match_counting ✅
ask 62: fetch_error_logs_with_errors ✅
ask 63: fetch_error_logs_no_errors ✅
ask 64: keda_vs_hpa_confusion ⚠️
ask 65: health_check_followup 🔧
investigate 01: oom_kill 🔧
investigate 02: crashloop_backoff 🔧
investigate 03: cpu_throttling ✅
investigate 04: image_pull_backoff 🔧
investigate 05: crashpod ✅
investigate 06: job_failure 🔧
investigate 07: job_syntax_error ✅
investigate 08: memory_pressure 🔧
investigate 09: high_latency 🔧
investigate 10: KubeDeploymentReplicasMismatch 🔧
investigate 11: KubePodCrashLooping 🔧
investigate 12: KubePodNotReady 🔧
investigate 13: Watchdog 🔧
investigate 14: tempo 🔧
investigate 15: dns_resolution ⚠️
investigate 16: dns_resolution_no_tool 🔧

Legend

  • ✅ the test was successful
  • ⚠️ the test failed but is known to be flaky or known to fail
  • 🔧 the test failed due to mock data issues (not a code regression)
  • ❌ the test failed and should be fixed before merging the PR

@aantn
aantn merged commit d2b26d1 into master Jul 23, 2025
@aantn
aantn deleted the remove-existing-log-handler branch July 23, 2025 17:58
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.

2 participants