From c8022fe6bebd1a339078dbc59850a8453fbc6170 Mon Sep 17 00:00:00 2001 From: antazoey Date: Thu, 6 Feb 2025 19:53:21 -0600 Subject: [PATCH] feat: `@ape.logging.silenced` decorator for ensuring an entire method does not log (#2495) --- src/ape/logging.py | 17 ++++++++++++++++- tests/functional/test_logging.py | 13 ++++++++++++- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/ape/logging.py b/src/ape/logging.py index 3010264d51..9869aa9c38 100644 --- a/src/ape/logging.py +++ b/src/ape/logging.py @@ -379,4 +379,19 @@ def get_rich_console(file: Optional[IO[str]] = None, **kwargs) -> "RichConsole": return _factory.get_console(file, **kwargs) -__all__ = ["DEFAULT_LOG_LEVEL", "logger", "LogLevel", "ApeLogger", "get_rich_console"] +def silenced(func: Callable): + """ + A decorator for ensuring a function does not output any logs. + + Args: + func (Callable): The function to call silently. + """ + + def wrapper(*args, **kwargs): + with logger.disabled(): + return func(*args, **kwargs) + + return wrapper + + +__all__ = ["DEFAULT_LOG_LEVEL", "logger", "LogLevel", "ApeLogger", "get_rich_console", "silenced"] diff --git a/tests/functional/test_logging.py b/tests/functional/test_logging.py index 204a6d2783..4656b66f3e 100644 --- a/tests/functional/test_logging.py +++ b/tests/functional/test_logging.py @@ -3,7 +3,7 @@ from click.testing import CliRunner from ape.cli import ape_cli_context -from ape.logging import LogLevel, logger, sanitize_url +from ape.logging import LogLevel, logger, sanitize_url, silenced @pytest.fixture @@ -147,3 +147,14 @@ def test_disabled(ape_caplog): # Show it is back. logger.error(message) assert message in ape_caplog.head + + +def test_silenced(ape_caplog): + @silenced + def method_to_silence(x: int, y: str): + logger.error(f"{x} {y}") + + magic = [156236, "Asd#g"] + unexpected = f"{magic[0]} {magic[1]}" + method_to_silence(*magic) + assert unexpected not in ape_caplog.head