2

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.

jpw
  • 18,697
  • 25
  • 111
  • 187
  • maybe you could create your own file like object, that delegates to the logger, and set `sys.stderr` equal to it? https://docs.python.org/2/library/stdtypes.html#file-objects – dm03514 Jan 26 '16 at 22:33
  • If you like the answer by `univerio`, why not mark it as accepted? – Vinay Sajip Jan 28 '16 at 19:10

1 Answers1

7

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.

univerio
  • 19,548
  • 3
  • 66
  • 68