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

feat: add logger.at_level context manager method #2294

Merged
merged 2 commits into from
Sep 19, 2024
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
20 changes: 19 additions & 1 deletion src/ape/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
import logging
import sys
import traceback
from collections.abc import Callable, Sequence
from collections.abc import Callable, Iterator, Sequence
from contextlib import contextmanager
from enum import IntEnum
from pathlib import Path
from typing import IO, Any, Optional, Union
Expand Down Expand Up @@ -185,6 +186,23 @@ def set_level(self, level: Union[str, int, LogLevel]):
for _logger in self._extra_loggers.values():
_logger.setLevel(level)

@contextmanager
def at_level(self, level: Union[str, int, LogLevel]) -> Iterator:
"""
Change the log-level in a context.

Args:
level (Union[str, int, LogLevel]): The level to use.

Returns:
Iterator
"""

initial_level = self.level
self.set_level(level)
yield
self.set_level(initial_level)

def log_error(self, err: Exception):
"""
Avoids logging empty messages.
Expand Down
9 changes: 9 additions & 0 deletions tests/functional/test_logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,3 +107,12 @@ def cmd(cli_ctx):
def test_set_level(level):
logger.set_level(level)
assert logger.level == LogLevel.INFO.value


def test_at_level():
level_to_set = next(lvl for lvl in LogLevel if lvl != logger.level)
initial_level = logger.level
with logger.at_level(level_to_set):
assert logger.level == level_to_set

assert logger.level == initial_level
Loading