Python新手:如何将异常日志打印到文件

时间:2014-02-19 01:29:11

标签: python

我是Python的新手,并尝试编写一个小程序将exeception堆栈放到一个文件中。有人可以让我知道为什么下面的代码不会将整个堆栈打印到文件中。 :

import logging

import traceback

def divlog(x,y):
    try:
        f = open("C:/files/divlog.txt", "a")
        f.write("{0:g} / {1:g} = {2:g} \n".format(x, y , (x/y) ) )
    except ZeroDivisionError:
        #f.write("Error : \n" , traceback.format_exc())
           raise 
    finally:
        f.close()

divlog(100,21)
divlog(20,5)
divlog(10, 0)
divlog(100,spam)

4 个答案:

答案 0 :(得分:2)

首先,open不应位于try..except的{​​{1}}内。最佳解决方案是尝试使用ZeroDivisionError语句来自动关闭文件。

with

其他一切看起来都是正确的。您很可能因尝试打开该文件而获得with open("C:/files/divlog.txt", "a") as f: try: f.write("{0:g} / {1:g} = {2:g} \n".format(x, y , (x/y) ) ) except ZeroDivisionError: f.write("Error : \n" + traceback.format_exc()) # <-- write takes 1 arg raise ,并且您的OSError

未抓住该文件

答案 1 :(得分:1)

虽然没有真正回答你的问题,但你可以对代码进行两次非常简单的改进,以避开你的问题:

首先,您应该使用Python logging module,因为不需要重新发明轮子。 Python附带电池,所以请使用它们!

其次,您应该考虑使用with X as Y代码结构来打开文件:

with open(file) as fd:
    fd.write("ook")

这将确保文件正确关闭。

答案 2 :(得分:0)

Python有一个名为sys的模块,其中sys.stdout和sys.stderr可以帮助您登录另一个文件

import logging
import sys
import traceback

f= open("C:\\AllReleases\\divlog1.txt", "a")
sys.stdout = f
sys.stderr = f
def divlog(x,y):
    try:

       f.write("{0:g} / {1:g} = {2:g} \n".format(x, y , (x/y) ) )
    except ZeroDivisionError:
       f.write("Error : \n" , traceback.format_exc())
       raise 

divlog(10,0) divlog(100,21) divlog(20,5) divlog(100,垃圾邮件)

f.close()

这将打开文件并在给定文件divlog1.txt

中写入运行和错误详细信息

答案 3 :(得分:0)

这似乎就是python logging模块的用途。

import logging
logging.basicConfig(filename='example.log',
                    level=logging.DEBUG)
logger = logging.getLogger(__name__)

def divlog(x,y):
    try:
        logger.info("{0:g} / {1:g} = {2:g} \n".format(x, y, x/y))
    except ZeroDivisionError:
        logger.exception("There was a division by zero")

def main():
    divlog(100,21)
    divlog(20,5)
    divlog(10, 0)

if __name__ == '__main__':
    main()

这会为您提供一个文件“example.log”,其中包含以下内容

INFO:__main__:100 / 21 = 4 

INFO:__main__:20 / 5 = 4 

ERROR:__main__:There was a division by zero
Traceback (most recent call last):
  File "test.py", line 8, in divlog
    logger.info("{0:g} / {1:g} = {2:g} \n".format(x, y, x/y))
ZeroDivisionError: integer division or modulo by zero

我们利用logging.exception函数捕获回溯并将其记录到文件中。请查看Official HowTo以获取更多详细信息和示例。