From 11158c58277b87011332c92d90e6350f2643a0c9 Mon Sep 17 00:00:00 2001 From: Delgan Date: Tue, 18 Feb 2025 12:42:15 +0100 Subject: [PATCH] Make "logger.catch()" usable as an async context manager --- CHANGELOG.rst | 1 + loguru/_logger.py | 6 ++++++ tests/test_exceptions_catch.py | 9 +++++++++ 3 files changed, 16 insertions(+) diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 1f575b8b7..1d48efc70 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -7,6 +7,7 @@ - Update the default log format to include the timezone offset since it produces less ambiguous logs (`#856 `_, thanks `@tim-x-y-z `_). - Honor the ``NO_COLOR`` environment variable to disable color output by default if ``colorize`` is not provided (`#1178 `_). - Add requirement for ``TERM`` environment variable not to be ``"dumb"`` to enable colorization (`#1287 `_, thanks `@snosov1 `_). +- Make ``logger.catch()`` usable as an asynchronous context manager (`#1084 `_). - Make ``logger.catch()`` compatible with asynchronous generators (`#1302 `_). diff --git a/loguru/_logger.py b/loguru/_logger.py index 5c2ba54a5..7f17f1a9a 100644 --- a/loguru/_logger.py +++ b/loguru/_logger.py @@ -1333,6 +1333,12 @@ def catch_wrapper(*args, **kwargs): functools.update_wrapper(catch_wrapper, function) return catch_wrapper + async def __aenter__(self): + return self.__enter__() + + async def __aexit__(self, type_, value, traceback_): + return self.__exit__(type_, value, traceback_) + return Catcher(False) def opt( diff --git a/tests/test_exceptions_catch.py b/tests/test_exceptions_catch.py index 71ebc2917..f06b83181 100644 --- a/tests/test_exceptions_catch.py +++ b/tests/test_exceptions_catch.py @@ -439,6 +439,15 @@ async def foo(): assert asyncio.run(foo()) == 42 +def test_async_context_manager(): + async def coro(): + async with logger.catch(): + return 1 / 0 + return 1 + + assert asyncio.run(coro()) == 1 + + def test_error_when_decorating_class_without_parentheses(): with pytest.raises(TypeError):