Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in python, how ensure any exceptions are logged with logger?

In a python app, how can I ensure that anything to stderr also goes to the logger, so if for example if the app crashes with an untrapped exception I can see that in the log?

My current logging setup is:

logger = logging.getLogger('myapp logger')
logger.setLevel(logging.INFO)
file_log_handler = logging.FileHandler('myapp.log')
logger.addHandler(file_log_handler)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
file_log_handler.setFormatter(formatter)
logger.addHandler(file_log_handler)

In the python logging docs I saw pretty much everything except how to send stderr to the logfile.

I know I can redirect stderr to a file like this:

sys.stderr = open('./myapp_errors.log', 'w')

However, I'm hoping to use logger to log exceptions so that (a) the formatting is consistent, and (b) I can log exceptions to the same file.

like image 795
jpw Avatar asked Feb 21 '26 14:02

jpw


1 Answers

You can override sys.excepthook to be your own handler. Then you can log to your own logger as you see fit:

import sys

def _excepthook(exctype, exc, tb):
    logger.error("An unhandled exception occurred.", exc_info=(exctype, exc, tb))

sys.excepthook = _excepthook

In fact, the default behavior of writing to stderr comes from the default value of sys.excepthook.

like image 157
univerio Avatar answered Feb 23 '26 04:02

univerio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!