Skip to content

Commit

Permalink
Change logging to use rich output
Browse files Browse the repository at this point in the history
- use dimmed coloring for stderr output to increase visibility
  • Loading branch information
ssbarnea committed Apr 17, 2023
1 parent e638247 commit 015c62f
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
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:
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,5 +1,6 @@
"""Tests for file utility functions."""
from __future__ import annotations
import logging

import os
import time
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

0 comments on commit 015c62f

Please sign in to comment.