简体   繁体   English

在Python中,将异常记录到文件的最佳方法是什么?

[英]In Python, what's the best way to log exceptions to a file?

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 而不是OD e你可以使用traceback.print_exc()来获得更详细的报告

You can use the traceback class. 您可以使用traceback类。

Like this: traceback.print_exc(file=open("errlog.txt","a")) 像这样: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. 或者,如果要在Django中记录异常,请查看此主题。

How do you log server errors on django sites 如何在django站点上记录服务器错误

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM