Delgan / loguru

Python logging made (stupidly) simple
MIT License
19.78k stars 695 forks source link

Silence @logger.catch() decorator if called from a try: block #723

Closed mpenning closed 1 year ago

mpenning commented 2 years ago

I'm testing this case, that arose while trying to fix a bug in ciscoconfparse which uses loguru.logger.catch() extensively...

Today I'm doing something like this for all methods / functions in ciscoconfparse...

Current case (called test.py):

from loguru import logger

@logger.catch(reraise=True)
def a_ccp_function():
    raise NotImplementedError()

def main():
    try:
        a_ccp_function()
    except:
        print("DONE1")
    finally:
        print("DONE2")

main()

Current output

$ python test.py
2022-10-15 13:35:42.019 | ERROR    | __main__:main:9 - An error has been caught in function 'main', process 'MainProcess' (40737), thread 'MainThread' (140585314334528):
Traceback (most recent call last):

  File "/home/mpenning/fixme/ciscoconfparse/test.py", line 9, in main
    a_ccp_function()
    └ <function a_ccp_function at 0x7fdc90deeaf0>

  File "/home/mpenning/fixme/ciscoconfparse/test.py", line 5, in a_ccp_function
    raise NotImplementedError()

NotImplementedError
DONE1
DONE2

I want to decorate a_ccp_function() with logger.catch(), but completely silence loguru output while inside a try: block.

Explicitly, I want stdout / stderr to look like this when a_ccp_function() is called in the example try block, above:

$ python test.py
DONE1
DONE2
$

How can I do this?

Delgan commented 2 years ago

This is not possible. You have to remove the @logger.catch().