Suppose I catch an exception, and I want to log it. How do I do that? Where do I specify where to log that to?
Asked
Active
Viewed 3,393 times
2 Answers
4
virhilo tmp $ cat l.py
import logging
logging.basicConfig(filename='exceptions.log', level=logging.DEBUG)
try:
1/0
except ZeroDivisionError as e:
logging.debug(e)
virhilo tmp $ python2 l.py
virhilo tmp $ cat exceptions.log
DEBUG:root:integer division or modulo by zero
virhilo tmp $
instead od e
you can use traceback.print_exc()
to get more detailed report

virhilo
- 6,568
- 2
- 29
- 26
-
It's probably worth linking to the logging module docs: http://docs.python.org/library/logging.html – Mike Axiak Jan 29 '11 at 17:28
-
Instead of logging "e", how do I log the entire traceback, using this method? – TIMEX Feb 01 '11 at 06:36
-
logging.debug(traceback.print_exc()) :) – virhilo Feb 01 '11 at 10:04
-
2@virhilo, you should use traceback.format_exc() if you want the string value - print_exc will print it to stdout – Peter Gibson Jul 06 '12 at 00:55
0
You can use the traceback class.
Like this: traceback.print_exc(file=open("errlog.txt","a"))
Here is an example (from here):
#!/usr/bin/env python
import sys, traceback
def main():
l=[1,2,3,4]
print l[4]
if __name__=="__main__":
try:
main()
except:
print "Trigger Exception, traceback info forward to log file."
traceback.print_exc(file=open("errlog.txt","a"))
sys.exit(1)
Or, if you want to log exceptions in Django, check out this thread.