>>> import logging
>>> #
>>> logging.basicConfig(level=logging.DEBUG,)
>>> logfile = logging.FileHandler('log.log')
>>> logfile.setLevel(level=logging.INFO)
>>> logging.getLogger('').addHandler(logfile)
>>> #
>>> mylogger = logging.getLogger('mylogger')
>>> #
>>> mylogger.info("an info message")
So far so good, but I'd like to record (possibly unhandled) exceptions
in the logfile.
* Do I need to explicitly trap every single exception ?
* In that case, won't I get 2 log messages on the console (as
illustrated in the code below:
>>> try:
>>> 1/0
>>> except ZeroDivisionError:
>>> mylogger.exception(":(")
>>> raise
Any comments/idea welcomed
Cheers.
> ... I'd like to record (possibly unhandled) exceptions in the logfile.
python myscript.py 2>error.log
Although it is usually not recommended to use a catch-all except, this
is the case where it might be useful. JUST DON'T FORGET TO RE-RAISE THE
EXCEPTION.
if __name__ == '__main__':
try:
main():
except Exception, e:
# log('Unhandled Exception', e)
raise
OK for a simple script, but the (unhandled) exceptions need to be
caught at the module level. Any idea?
Override sys.excepthook. http://docs.python.org/library/sys.html#sys.excepthook