Hide all console output of an unhandled exception

38 Views Asked by At

I catch all the exceptions and log them with loguru logger. I then have to reraise the same exception to fail the step and send the info to elastic.

from loguru import logger

@when('some step ...')
def do_something(context, ...):
   try:
       ...
   except Exception as e:
     save_traceback_to_log_file()
     logger.error("Example exception log.")
     raise e

------------------------
Console output:
...
... Example exception log.

I only want to see the log from loguru. I don't want any traceback or message of the exception from raising an unhandled exception in the console output.

I was able to silence traceback with:

@contextmanager
def disable_traceback():
    default_value = getattr(sys, "tracebacklimit", 1000)
    sys.tracebacklimit = 0
    yield
    sys.tracebacklimit = default_value
    ...
    with disable_traceback():
      raise e

But I still get the unwanted exception message in console output:

raise Exception("Some message...")

04.12.1999  15:36:47.153 | ERROR    | ... - Exception - Some message...
    When executing the system test "..." ... failed in 0.503s
Exception: Some message...   << don't want

None of these seem to work: sys.excepthook, silencing Python's stderr with open(os.devnull, 'w'), capture decorator

How do I do it?

1

There are 1 best solutions below

0
elebur On

Not sure why sys.excepthook didn't work for you but it is exactly what you are looking for, IMHO. See the simple example below.

Note: sys.excepthook doesn't work with IPython. See this question.

import sys
from loguru import logger


def exception_handler(type, value, traceback):
   pass
sys.excepthook = exception_handler

def func():
   try:
     1/0
   except Exception as ex:
     logger.error("error hello")
     raise ex

func()

The output:

2024-01-07 12:12:11.791 | ERROR    | __main__:func:13 - error hello