python log文档

来源:互联网 发布:mac新系统 编辑:程序博客网 时间:2024/05/21 09:35

在使用python的过程中,错误检查一直都是个大难题,这里提供一种打印log文件的方式,</span>

即记录python运行过程的文档,能够有效的帮助你定位错误

代码:

import mprintlogfile = 'setup.log'log = mprint.MPRINT(logfile,'w')log._print("error")

可以再你需要的任何地方使用log._print() 输出内容

mprint 模块是一个自定义模块,其内容如下:

import sysimport osimport re#-------------------------------------------------------------------------------#-------------------------------------------------------------------------------#-------------------------------------------------------------------------------class MPRINT:   """This class encapsulates standard print statement.   """#-------------------------------------------------------------------------------   def __init__(self, filename, mode='a'):      """filename : name of log file ; mode = 'w'/'a'      """      self.mode   = mode      self.stderr = sys.stderr      self.logf   = [sys.stdout]      debug_name = filename.replace('.log', '.dbg')      filename = [filename, debug_name]      for filen_i in filename:         nmax = 100         for i in range(nmax, -1, -1):            if i > 0:               fich = '%s.%d' % (filen_i, i)            else:               fich = filen_i            if os.path.exists(fich):               if i == nmax:                  os.remove(fich)               else:                  os.rename(fich, '%s.%d' % (filen_i, i+1))         self.logf.append(open(filen_i, mode))      sys.stderr  = self.logf[1]      self.last_char = [os.linesep,] * 3#-------------------------------------------------------------------------------   def close(self):      """Close file properly on deletion.      """      sys.stderr = self.stderr      for f in self.logf[1:]:         f.close()#-------------------------------------------------------------------------------   def _print(self, *args, **kargs):      """print replacement.      Optionnal argument :       term  : line terminator (default to os.linesep).      """      term = kargs.get('term', os.linesep)      for i, f in enumerate(self.logf):         if kargs.get('DBG') and i != 2:            continue         if type(f) is file:            l_val = []            for a in args:               if type(a) in (str, unicode):                  l_val.append(a)               else:                  l_val.append(repr(a))            txt = ' '.join(l_val)            txt = txt.replace(os.linesep+' ',os.linesep)            if kargs.get('DBG'):               lines = txt.splitlines()               if self.last_char[i] != os.linesep:                  lines.insert(0, '')               else:                  lines[0] = '<DBG> ' + lines[0]               txt = (os.linesep + '<DBG> ').join(lines)            txt = txt + term            f.write(txt)            f.flush()            if len(txt) > 0:               self.last_char[i] = txt[-1]         else:            print 'Unexpected object %s : %s' % (type(f), repr(f))


0 0