python整理十三——迷你日志

写个小点的程序,写日志太麻烦了,大点的程序,不写日志是万万不行的,鉴于日志频繁的使用,对python的logging稍微封装一下,适合自己的需求:

 

 

  1. #coding=utf-8
  2. import os, logging, sys
  3. from logging.handlers import RotatingFileHandler as RFHandler
  4. class CommLogger:
  5.     
  6.     LOG_FILE_SIZE_MAX    = 1024  # byte
  7.     LOG_FILE_BACKUP_MAX  = 5 
  8.     def __init__(self):
  9.         self.__log_argv = {'dirname'      : os.path.join(os.path.dirname(__file__), 'log' ),
  10.                            'name_default' : 'log_default',
  11.                            'extend'       : '.log',
  12.                            }
  13.         self.__log_fmt_t = '%(f_info)s%(ctrl)s%(ctime)s%(ctrl)s%(msg)s%(ctrl)s%(tail)s%(ctrl)s' % /
  14.             {'f_info' : 'File:%(pathname)s,line %(lineno)d,function: %(funcName)s',    
  15.              'ctime'  : '%(asctime)s [%(levelname)s]',     
  16.              'msg'    : '%(message)s'
  17.              'tail'   : '-' * 80 ,
  18.              'ctrl'   : os.linesep,}
  19.         self.__log_fmt = logging.Formatter(self.__log_fmt_t)
  20.         self.__loggers = {}
  21.     def __getLogPath(self, log_name):
  22.         fpath = os.path.join(self.__log_argv['dirname'], log_name)
  23.         if not os.path.exists(fpath):
  24.             os.makedirs(fpath)
  25.         return fpath
  26.     def __initLog(self, log_name, level, bPrint):
  27.         if log_name not in self.__loggers:
  28.             logger = logging.getLogger(log_name)
  29.             if len(logger.handlers) == 0:
  30.                 if bPrint:
  31.                     chdlr = logging.StreamHandler(sys.stdout)
  32.                     chdlr.setFormatter(self.__log_fmt)
  33.                     logger.addHandler(chdlr) 
  34.                 else:
  35.                     fname = os.path.join(self.__getLogPath(log_name), log_name + self.__log_argv['extend'])
  36.                     fhdlr = RFHandler(fname, 'a', CommLogger.LOG_FILE_SIZE_MAX, CommLogger.LOG_FILE_BACKUP_MAX,)
  37.                     fhdlr.setFormatter(self.__log_fmt)
  38.                     logger.addHandler(fhdlr)
  39.                 logger.setLevel(level)
  40.                 self.__loggers[log_name] = logger  
  41.         return self.__loggers[log_name]
  42.     
  43.     def getLogger(self, log_name = None, bPrint = False, level= logging.DEBUG, ):
  44.         if log_name is None:
  45.             log_name = self.__log_argv['name_default']
  46.         if log_name not in self.__loggers:
  47.             self.__initLog(log_name, level, bPrint)
  48.         return self.__loggers[log_name]
  49. def mini_log(fn):
  50.     def moniter(*args, **argkv):
  51.         return fn(*args, **argkv)
  52.     logger = CommLogger().getLogger(fn.func_name)
  53.     log_info = {'fn_name' : repr(fn.func_name), 'fn_code' : fn.func_code, 'ctrl' : os.linesep}
  54.     logger.info('The function of %(fn_name)s has been running.%(ctrl)s%(fn_code)s' % log_info)
  55.     return moniter    
  56. @mini_log
  57. def test():
  58.     print 'test logging module.'
  59. if __name__ == '__main__':
  60.     cCls = CommLogger()
  61.     log0 = cCls.getLogger()
  62.     log1 = cCls.getLogger('log1'True)
  63.     for i in range(3):
  64.         log0.debug('debug')
  65.         log0.info('info')
  66.         log0.warning('warn')
  67.         log0.error('error')
  68.         log0.critical('critical')
  69.         
  70.         log1.debug('debug')
  71.         log1.info('info')
  72.         log1.warn('warn')
  73.         log1.error('error')
  74.         log1.critical('critical')        
  75.     test()
  76.     print 'end___'
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值