Hide all unhandled exception console output

108 Views Asked by At

I catch all the exceptions and log them with loguru logger. I then have to reraise the exception.

from loguru import logger

except Exception as e:
  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.

How do I do it?

2

There are 2 best solutions below

0
matszwecja On
  1. Redirect loguru to stdout instead of stderr:
logger.add(sys.stdout, format="...")
  1. Silence Python's stderr
import os
import sys
f = open(os.devnull, 'w')
sys.stderr = f

Take note that it completely silences stderr from this process, so it cause unintended changes to any other module also using stderr.

0
Erdit On

A way to suppress the exception handler is to override it. Python lets you set a custom function to handle uncaught exceptions. Meaning you can log the exception without printing the traceback.

Here's a small example:

import sys
from loguru import logger

def handle_exception(exc_type, exc_value, exc_traceback):
    if issubclass(exc_type, KeyboardInterrupt): #handle "CTRL+C", you probably still want this.
        sys.__excepthook__(exc_type, exc_value, exc_traceback)
        return

    logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback))

sys.excepthook = handle_exception

# ...

Suppressing the traceback and exception details may make it harder to understand and fix issues, assuming you're aware of this, the above implementation should work for your case.