2011-04-15 47 views
2

如何只打印例外using python存在于/tmp/exceptions.log忽略所有异常的调试statements.The快照下面给出一个文件..打印例外

 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/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 

回答

1

最简单的方法是使用带有排除标志的grep,例如

grep -v DEBUG /tmp/exceptions.log 

这将打印行包含“调试”字符串。

0
>>> 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'] 
>>> 
0

你也可以使用PyLog中的“logview”。如果您查看PyWorkbooks的最新版本(此处为https://sourceforge.net/projects/pyworkbooks/),则会有一个easy_log文件设置日志记录应用程序的日志记录。

logview是一个很好的GUI,并允许你做一些事情,如过滤器输入。

0

如果您使用try-除了结构,你可以这样做:

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