2010-12-19

python service exception logging

I run a few python services through GNU screen; the problem is that if/when they crash, the exception and stack trace information is lost, the screen exits, and I need to manually restart them. Here's some template code I've started using to improve that situation: import logging, traceback log_fn = 'except.log' log_fmt = '%(asctime)s\t%(message)s' log_dfmt = '%Y-%m-%d %H:%M:%S' logging.basicConfig(filename=log_fn, level=logging.DEBUG, format=log_fmt, datefmt=log_dfmt) console = logging.StreamHandler() console.setLevel(logging.DEBUG) fmtr = logging.Formatter(log_fmt, log_dfmt) console.setFormatter(fmtr) logging.getLogger('').addHandler(console) while True: try: run() except KeyboardInterrupt: raise except: logging.error(traceback.format_exc()) pass