Logging exceptions to a file

Lie Ryan lie.1296 at gmail.com
Thu May 7 05:32:38 EDT 2009


Pierre GM wrote:
> All,
> I need to log messages to both the console and a given file. I use the
> following code (on Python 2.5)
> 
>>>> 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.
> 

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



More information about the Python-list mailing list