I would like to disable the stack trace that is printed when there is an exception raised.
Whenever the code calls the logger.exception method, the stack trace is automatically printed.
That's because the default value of the exc_info parameter of the .exception method is True.
See the source code:
def exception(msg, *args, exc_info=True, **kwargs):
"""
Log a message with severity 'ERROR' on the root logger, with exception
information. If the logger has no handlers, basicConfig() is called to add
a console handler with a pre-defined format.
"""
error(msg, *args, exc_info=exc_info, **kwargs)
To prevent this, you can send exc_info=False to the .exception method like this:
try:
raise Exception("Huston we have a problem!")
except Exception as ex:
logger.exception(f"Looks like they have a problem: {ex}", exc_info=False)
While this seems like working, it is bad to force users to write exc_info=False each time they use that method. Therefore, in order to take this burden from the shoulders of the programmers, you can monkey patch the .exception method and make it act like a regular .error method like this:
# somewhere in the start of your program
# money patch the .exception method
logger.exception = logger.error
try:
raise Exception("Huston we have a problem!")
except Exception as ex:
logger.exception(f"Looks like they have a problem: {ex}")
Looking around I found the following solution / workaround:
sys.tracebacklimit = 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With