当异常发生时使用python将其写入文件中

时间:2013-07-11 09:52:18

标签: python try-except

我只想在文件中编写异常详细信息:我试过如下“

def WriteErrorLog(e) :
   global lcnt

   lstErr=[]

   iUrlfOutputFile = open("C:\Error.log", "a")
   csvUrlfInfoWriter = csv.writer(iUrlfOutputFile,  delimiter=',', lineterminator='\n')
   exc_type, exc_obj, exc_tb = sys.exc_info()
   fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
   csvUrlfInfoWriter.writerow('[Exc_Type, FileName, Script_Line No,InputFile_LineNo]')
   lstErr.append(exc_type)
   lstErr.append(fname)
   lstErr.append(g_lcnt)
   for value in lstErr :
       csvUrlfInfoWriter.writerow(value)

   iUrlfOutputFile.close()

除了块:

 except Exception as e :
        WriteErrorLog(e)

它不起作用,有人可以纠正我吗?或者可以建议更好的选择? 谢谢!

1 个答案:

答案 0 :(得分:2)

我会使用Python Loggin - > http://docs.python.org/2/library/logging.html 您可以将其行格式化为“,”分隔,例如

[formatter_generic_form]
format='%(asctime)s , %(levelname)s , %(message)s'
datefmt='%Y-%m-%d %H:%M:%S'

Datetime,level_of_log,whatever_message_you_want_to_log

我建议你http://docs.python.org/2/howto/logging.html#logging-basic-tutorial开始