Ultimately i'm trying to write a custom logging module to log the events of some unmanned daily scripts, and currently i'm looking at how to log exceptions.
Several other SO questions have suggested replacing sys.excepthook with a function to achieve this, but I couldn't get this to work as intended inside my module so now i'm just trying to get a basic example working so I can start to understand what's happening here.
in python, how ensure any exceptions are logged with logger?
The above question outlines some code they've used to achieve this which is similar/identical to acceptable answers in other SO questions, but none seem to work for me.
Here is my code:
import logging
import sys
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)
def _excepthook(exctype, exc, tb):
logger.error("An unhandled exception occurred.", exc_info=(exctype, exc, tb))
sys.excepthook = _excepthook
logger.debug("Hello")
5/0 # error
logger.debug("what")
I'm expecting this to print the details of the ZeroDivisionError to 'myapp.log' but when running from within VS Code, the ZeroDivisionError exception is raised as normal and nothing is printed to 'myapp.log'.
Does anyone know where i'm going wrong or how I should be thinking about/approaching this?
A super simple example of replacing sys.excepthook to do anything other than its default behavior would be greatly appreciated.