Skip to content

Commit

Permalink
Make "logger.catch()" usable as an async context manager
Browse files Browse the repository at this point in the history
  • Loading branch information
Delgan committed Feb 18, 2025
1 parent 7748b6c commit 11158c5
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
- 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>`_).
- 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>`_).
- 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>`_).
- Make ``logger.catch()`` usable as an asynchronous context manager (`#1084 <https://github.com/Delgan/loguru/issues/1084>`_).
- Make ``logger.catch()`` compatible with asynchronous generators (`#1302 <https://github.com/Delgan/loguru/issues/1302>`_).


Expand Down
6 changes: 6 additions & 0 deletions loguru/_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
9 changes: 9 additions & 0 deletions tests/test_exceptions_catch.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):

Expand Down

0 comments on commit 11158c5

Please sign in to comment.