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

Change logging to use rich output #3297

Merged
merged 1 commit into from
Apr 17, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion src/ansiblelint/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,19 @@
_logger = logging.getLogger(__name__)


class LintLogHandler(logging.Handler):
"""Custom handler that uses our rich stderr console."""

def emit(self, record: logging.LogRecord) -> None:
try:
msg = self.format(record)
console_stderr.print(f"[dim]{msg}[/dim]", highlight=False)
except RecursionError: # See issue 36272
raise
except Exception: # pylint: disable=broad-exception-caught
self.handleError(record)


def initialize_logger(level: int = 0) -> None:
"""Set up the global logging level based on the verbosity number."""
# We are about to act on the root logger, which defaults to logging.WARNING.
Expand All @@ -78,7 +91,7 @@ def initialize_logger(level: int = 0) -> None:
2: logging.DEBUG,
}

handler = logging.StreamHandler()
handler = LintLogHandler()
formatter = logging.Formatter("%(levelname)-8s %(message)s")
handler.setFormatter(formatter)
logger = logging.getLogger()
Expand Down
7 changes: 6 additions & 1 deletion test/test_file_utils.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Tests for file utility functions."""
from __future__ import annotations

import logging
import os
import time
from argparse import Namespace
Expand Down Expand Up @@ -105,13 +106,15 @@ def test_discover_lintables_silent(
is_in_git: bool,
monkeypatch: MonkeyPatch,
capsys: CaptureFixture[str],
caplog: LogCaptureFixture,
) -> None:
"""Verify that no stderr output is displayed while discovering yaml files.

(when the verbosity is off, regardless of the Git or Git-repo presence)

Also checks expected number of files are detected.
"""
caplog.set_level(logging.FATAL)
options = cli.get_config([])
test_dir = Path(__file__).resolve().parent
lint_path = test_dir / ".." / "examples" / "roles" / "test-role"
Expand All @@ -125,7 +128,9 @@ def test_discover_lintables_silent(
monkeypatch.chdir(str(lint_path))
files = file_utils.discover_lintables(options)
stderr = capsys.readouterr().err
assert not stderr, "No stderr output is expected when the verbosity is off"
assert (
not stderr
), f"No stderr output is expected when the verbosity is off, got: {stderr}"
assert (
len(files) == yaml_count
), "Expected to find {yaml_count} yaml files in {lint_path}".format_map(
Expand Down