Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Logging exceptions to a file

3 views
Skip to first unread message

Pierre GM

unread,
May 6, 2009, 11:51:35 PM5/6/09
to
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.

Lawrence D'Oliveiro

unread,
May 7, 2009, 2:43:02 AM5/7/09
to
In message <597627b8-
d30b-4b74-920...@s28g2000vbp.googlegroups.com>, Pierre GM wrote:

> ... I'd like to record (possibly unhandled) exceptions in the logfile.

python myscript.py 2>error.log


Lie Ryan

unread,
May 7, 2009, 5:32:38 AM5/7/09
to

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

Pierre GM

unread,
May 7, 2009, 9:19:02 AM5/7/09
to

OK for a simple script, but the (unhandled) exceptions need to be
caught at the module level. Any idea?

segfaulthunter

unread,
May 7, 2009, 12:56:16 PM5/7/09
to
0 new messages