python中写日志
时间:2009-01-21 来源:hkebao
1.写一个日志操作的类代码如下:
import sys,string
import time
"""
log into logfile
usage:
log = Log()
log.config('my.log')
log.log("Error 443")
"""
class Log:
logfile = '';
def config(self,_logfile): #调用这个方法实现判断日志文件位置
if _logfile != '':
self.logfile = _logfile;
else:
self.logfile = 'run.log';
def log(self,_msg): #调用此方法实现保存记录到文件中去
now = time.time()
strtime = str(time.localtime(now)[0]) + '-' + str(time.localtime(now)[1]) \
+ '-' + str(time.localtime(now)[2]) \
+ ' ' + str(time.localtime(now)[3]) \
+ ':' + str(time.localtime(now)[4]) \
+ ':' + str(time.localtime(now)[5]);
msg = strtime + ' ' + _msg + '\n';
try:
logfilehandle = open(self.logfile,'a+');#返回一个文件句柄的
logfilehandle.write(msg);#write file
logfilehandle.close();
except:
exit(0);
from log import Log
class Module:
log = Log()
logfile='test.log'
def Test(self):
try:
a = 1/0
except Exception,e:
self.log.config(self.logfile)
self.log.log(str(e))
if __name__ == '__main__':
ob = Module()
ob.Test()
在其他的类中如果要调用就直接这样就可以了,好方便的哦!
通过写日志可以将一些异常信息写到文本中去这样比较方便的哦!
import sys,string
import time
"""
log into logfile
usage:
log = Log()
log.config('my.log')
log.log("Error 443")
"""
class Log:
logfile = '';
def config(self,_logfile): #调用这个方法实现判断日志文件位置
if _logfile != '':
self.logfile = _logfile;
else:
self.logfile = 'run.log';
def log(self,_msg): #调用此方法实现保存记录到文件中去
now = time.time()
strtime = str(time.localtime(now)[0]) + '-' + str(time.localtime(now)[1]) \
+ '-' + str(time.localtime(now)[2]) \
+ ' ' + str(time.localtime(now)[3]) \
+ ':' + str(time.localtime(now)[4]) \
+ ':' + str(time.localtime(now)[5]);
msg = strtime + ' ' + _msg + '\n';
try:
logfilehandle = open(self.logfile,'a+');#返回一个文件句柄的
logfilehandle.write(msg);#write file
logfilehandle.close();
except:
exit(0);
from log import Log
class Module:
log = Log()
logfile='test.log'
def Test(self):
try:
a = 1/0
except Exception,e:
self.log.config(self.logfile)
self.log.log(str(e))
if __name__ == '__main__':
ob = Module()
ob.Test()
在其他的类中如果要调用就直接这样就可以了,好方便的哦!
通过写日志可以将一些异常信息写到文本中去这样比较方便的哦!
相关阅读 更多 +