Skip to content

Commit f64b9e3

Browse files
authored
Make "logger.catch()" usable as an async context manager (#1304)
1 parent 7748b6c commit f64b9e3

File tree

3 files changed

+16
-0
lines changed

3 files changed

+16
-0
lines changed

CHANGELOG.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
- Update the default log format to include the timezone offset since it produces less ambiguous logs (`#856 <https://github.com/Delgan/loguru/pull/856>`_, thanks `@tim-x-y-z <https://github.com/tim-x-y-z>`_).
88
- Honor the ``NO_COLOR`` environment variable to disable color output by default if ``colorize`` is not provided (`#1178 <https://github.com/Delgan/loguru/issues/1178>`_).
99
- Add requirement for ``TERM`` environment variable not to be ``"dumb"`` to enable colorization (`#1287 <https://github.com/Delgan/loguru/pull/1287>`_, thanks `@snosov1 <https://github.com/snosov1>`_).
10+
- Make ``logger.catch()`` usable as an asynchronous context manager (`#1084 <https://github.com/Delgan/loguru/issues/1084>`_).
1011
- Make ``logger.catch()`` compatible with asynchronous generators (`#1302 <https://github.com/Delgan/loguru/issues/1302>`_).
1112

1213

loguru/_logger.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1333,6 +1333,12 @@ def catch_wrapper(*args, **kwargs):
13331333
functools.update_wrapper(catch_wrapper, function)
13341334
return catch_wrapper
13351335

1336+
async def __aenter__(self):
1337+
return self.__enter__()
1338+
1339+
async def __aexit__(self, type_, value, traceback_):
1340+
return self.__exit__(type_, value, traceback_)
1341+
13361342
return Catcher(False)
13371343

13381344
def opt(

tests/test_exceptions_catch.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -439,6 +439,15 @@ async def foo():
439439
assert asyncio.run(foo()) == 42
440440

441441

442+
def test_async_context_manager():
443+
async def coro():
444+
async with logger.catch():
445+
return 1 / 0
446+
return 1
447+
448+
assert asyncio.run(coro()) == 1
449+
450+
442451
def test_error_when_decorating_class_without_parentheses():
443452
with pytest.raises(TypeError):
444453

0 commit comments

Comments
 (0)