diff --git a/src/ansiblelint/__main__.py b/src/ansiblelint/__main__.py index aec455d6ac..a9e8effd55 100755 --- a/src/ansiblelint/__main__.py +++ b/src/ansiblelint/__main__.py @@ -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. @@ -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() diff --git a/test/test_file_utils.py b/test/test_file_utils.py index a135b94a74..9b595d2498 100644 --- a/test/test_file_utils.py +++ b/test/test_file_utils.py @@ -1,6 +1,7 @@ """Tests for file utility functions.""" from __future__ import annotations +import logging import os import time from argparse import Namespace @@ -105,6 +106,7 @@ 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. @@ -112,6 +114,7 @@ def test_discover_lintables_silent( 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" @@ -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(