2008年12月9日星期二

How to print __LINE__ and timestamp in Python log

import inspect
import datetime
import time

def log(filename):
   import os
   if not os.path.exists('Log') or not os.path.isdir('Log'):
      os.mkdir('Log')
   f = open('Log/%s.log'%filename, 'w')
   return f

def PrintMsg(msg):
    timestamp = _gettime()
    msg = '%s %5s --> ## %s' %(timestamp(), inspect.getouterframes(inspect.currentframe())[1][2], msg)
    print msg

def PrintLog(fp, msg, flag=None):
    ''' Use to print log for each task. We can use some flag to add extra
    information to the output message.
   "inspect.getouterframes(inspect.currentframe())[1][2]" can't be put
   in a nested subcall, otherwise the __LINE__ will be the nested subcall's
   call line.
   '''
   timestamp = _gettime()
   if not flag:
      printlog(fp, msg)
   elif flag == 'DT':
      msg = '%s %5d --> Download Task :: %s' %(timestamp(),  inspect.getouterframes(inspect.currentframe())[1][2], msg)
   elif flag == 'MT':
       msg = '%s %5d --> Main Task :: %s' %(timestamp(), inspect.getouterframes(inspect.currentframe())[1][2], msg)
   elif flag == 'ST':
      msg = '%s %5d --> SrchPort Task :: %s' %(timestamp(), inspect.getouterframes(inspect.currentframe())[1][2], msg)
   elif flag == 'CT':
      msg = '%s %5d --> Command Task :: %s' %(timestamp(), inspect.getouterframes(inspect.currentframe())[1][2], msg)
   else:
      pass
   _print_log(fp, msg)

def _gettime():
   '''To get the timestamp. 'lambda' is a perfect way to do this kind of job.
   '''
   return lambda: datetime.datetime.fromtimestamp(time.time())

if __name__ == '__main__':
   _msg = 'hello devan'
   f = open('testtttt.log', 'a')
   PrintMsg(_msg)
   PrintLog(f, _msg, 'DT')

没有评论: