loguru icon indicating copy to clipboard operation
loguru copied to clipboard

Suppressing stack trace for logger.catch()

Open injust opened this issue 3 years ago • 6 comments

Is there a way to suppress the stack trace for logger.catch()?

I have a decorator that catches certain types of exceptions and calls logger.exception() or logger.error(), depending on a debug boolean value. I'm trying to rewrite it using logger.catch(), but it always outputs the full stack trace.

injust avatar Apr 19 '21 23:04 injust

The stack trace formatting depends on the backtrace parameter of your sink (it defaults to True).

Does logger.add(sys.stderr, backtrace=False) produces the expected output?

Delgan avatar Apr 20 '21 19:04 Delgan

Doesn't seem to help; I still get the full stack trace.

Would this (from 0.3.1 changelog) be relevant?

Ensure stack from the caller is displayed while formatting exception of a function decorated with @logger.catch when backtrace=False.

injust avatar Apr 20 '21 19:04 injust

I don't think it's related to this statement in the changelog.

Did you try also with diagnose=False? On my computer it works as expected:

from loguru import logger
import sys

@logger.catch
def bar():
    1 / 0

def foo():
    bar()

logger.remove()
logger.add(sys.stderr, backtrace=False, diagnose=False)
foo()
2021-04-20 22:32:27.132 | ERROR    | __main__:foo:9 - An error has been caught in function 'foo', process 'MainProcess' (260023), thread 'MainThread' (140010475808576):
Traceback (most recent call last):
  File "/home/delgan/Programmation/loguru/a.py", line 9, in foo
    bar()
  File "/home/delgan/Programmation/loguru/a.py", line 6, in bar
    1 / 0
ZeroDivisionError: division by zero

Isn't the output you're looking for?

Delgan avatar Apr 20 '21 20:04 Delgan

Not exactly. I'm trying to suppress the stack trace entirely, so the only line that is output is:

2021-04-20 22:32:27.132 | ERROR    | __main__:foo:9 - [message]

as if I had caught and logged the error manually using logger.error(e) instead of logger.exception(e).

injust avatar Apr 23 '21 17:04 injust

Okay, sorry, I get it! Indeed, it is not possible to completely remove the stacktrace with logger.catch(). You implemented a custom context manager and that's the best thing to do I think.

Delgan avatar Apr 24 '21 11:04 Delgan

@Delgan Can you accept PR for this?
I thought about adding backtrace parameter to logger.catch() and check it to set backtrace_ to None in Catcher

a5r0n avatar Mar 25 '22 01:03 a5r0n