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.
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
.