Recently wrote a program that allows you to get a list of folders and files that are updated for a specified folder, and do something based on the list of updates that you get. Because the program is written on the server running, in order to ensure that the program in the process of running, from time to time out of some unusual information to frighten other users, in the program added exception handling. Organize the online data and try to use Sys.exce_info () and Traceback. The effect is not bad, the following information is my current way of handling exceptions, where type is the type of exception, value is the cause of the exception, Traceback is through the traceback after the exception information, can be positioned to cause the exception of the code.
2016-11-07 22:07:56
-------------------------------
Type: <type ' exceptions. TypeError ' >
Value:string indices must is integers, not str
Traceback: [(' filename ', line number, ' function name ', ' code line with exception ')]
In Try...except, the following two lines are used to record an exception condition. You need to look at specific requirements for how your program will continue after an exception occurs.
TP,VAL,TD = Sys.exc_info ()
Log.logerexception (TP,VAL,TD)
The specific code is as follows
1 Import OS
2 Import Time
3 Import Traceback
4 Import Sys
5
6 def logerexception (TP,VAL,TD):
7 etype = STR (TP)
8 Evalue = str (val)
9 ETB = TRACEBACK.EXTRACT_TB (TD)
Ten errormsg = "type:" + etype + "\ n"
One errormsg + = "Value:" + evalue + "\ n"
ErrorMsg + = "Traceback:" + str (ETB) + "\ n"
WriteToFile (ERRORMSG)
14
def writetofile (errormsg):
LogFilePath = Os.path.abspath ('. ') + "/log"
If not os.path.exists (LogFilePath):
Os.mkdir (LogFilePath)
19
LogFile = Time.strftime ("%y%m%d", Time.localtime ()) + ". txt"
fp = open (LogFilePath + "/" + logfile, "a")
isotimeformat= "%y-%m-%d%x"
Happeningtime = Time.strftime (Isotimeformat, Time.localtime ())
Usermsg = ""
Usermsg + = happeningtime + "\ n-------------------------------\ n"
Usermsg + + errormsg
Fp.write (usermsg + "\ n")
Fp.close ()