Print exceptions in a file
How to print only the exceptions using python
that is present in a file /tmp/exceptions.log ignoring all the debug statements.The snapshot of the exception is given below..
Traceback (most recent call last):
File "/usr/site/bank/views.py", line 1695, in importmydata
o.save()
File "/usr/site/cl/django/django/db/models/base.py", line 435, in save
self.save_base(using=using, force_insert=force_insert, force_update=force_update)
IntegrityError: (1048, "Column 'option_b' cannot be null")
2011-04-14 11:57:40,895 DEBUG In exception
2011-04-14 11:57:40,915 DEBUG No resource found
2011-04-14 11:57:40,926 DEBUG Name
2011-04-14 11:57:40,915 DEBUG No resource found
2011-04-14 11:57:40,915 DEBUG No resource found
2011-04-14 11:57:40,915 DEBUG No resource found
2011-04-14 11:57:40,915 DEBUG No resource found
Traceback (most recent call last):
File "/usr/site/ba开发者_开发技巧nk/views.py", line 1695, in importmydata
o.save()
File "/usr/site/cl/django/django/db/models/base.py", line 435, in save
self.save_base(using=using, force_insert=force_insert, force_update=force_update)
IntegrityError: (1048, "Column 'option_b' cannot be null")
2011-04-14 11:57:40,895 DEBUG In exception
2011-04-14 11:57:40,915 DEBUG No resource found
2011-04-14 11:57:40,926 DEBUG Name
The simplest way is to use grep with exclusion flag , e.g.
grep -v DEBUG /tmp/exceptions.log
This will print the lines that don't contain the "DEBUG" string.
>>> import re
>>> pat = re.compile(r'(\w+:\s.*\n)')
>>> pat.findall(c) # c is your logs content
['IntegrityError: (1048, "Column \'option_b\' cannot be null")\n', 'IntegrityError: (1048, "Column \'option_b\' cannot be null")\n']
>>>
you could also use "logview", available in the PyPI. If you look at the most recent version of my code for PyWorkbooks (here https://sourceforge.net/projects/pyworkbooks/), there is an easy_log file that sets up logging to the logview application.
logview is an excellent gui and allows you to do things like filter inputs.
If you are using try-except structure you can do something like:
try:
foo()
except Exception,ex:
print "Exception %s"%str(ex) # Output exception
print "Unexpected error:", sys.exc_info()[0] # Exception message
import traceback
traceback.print_exc() # Output full traceback if you want one
精彩评论