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?
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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.