写个小点的程序,写日志太麻烦了,大点的程序,不写日志是万万不行的,鉴于日志频繁的使用,对python的logging稍微封装一下,适合自己的需求:
- #coding=utf-8
- import os, logging, sys
- from logging.handlers import RotatingFileHandler as RFHandler
- class CommLogger:
- LOG_FILE_SIZE_MAX = 1024 # byte
- LOG_FILE_BACKUP_MAX = 5 #
- def __init__(self):
- self.__log_argv = {'dirname' : os.path.join(os.path.dirname(__file__), 'log' ),
- 'name_default' : 'log_default',
- 'extend' : '.log',
- }
- self.__log_fmt_t = '%(f_info)s%(ctrl)s%(ctime)s%(ctrl)s%(msg)s%(ctrl)s%(tail)s%(ctrl)s' % /
- {'f_info' : 'File:%(pathname)s,line %(lineno)d,function: %(funcName)s',
- 'ctime' : '%(asctime)s [%(levelname)s]',
- 'msg' : '%(message)s',
- 'tail' : '-' * 80 ,
- 'ctrl' : os.linesep,}
- self.__log_fmt = logging.Formatter(self.__log_fmt_t)
- self.__loggers = {}
- def __getLogPath(self, log_name):
- fpath = os.path.join(self.__log_argv['dirname'], log_name)
- if not os.path.exists(fpath):
- os.makedirs(fpath)
- return fpath
- def __initLog(self, log_name, level, bPrint):
- if log_name not in self.__loggers:
- logger = logging.getLogger(log_name)
- if len(logger.handlers) == 0:
- if bPrint:
- chdlr = logging.StreamHandler(sys.stdout)
- chdlr.setFormatter(self.__log_fmt)
- logger.addHandler(chdlr)
- else:
- fname = os.path.join(self.__getLogPath(log_name), log_name + self.__log_argv['extend'])
- fhdlr = RFHandler(fname, 'a', CommLogger.LOG_FILE_SIZE_MAX, CommLogger.LOG_FILE_BACKUP_MAX,)
- fhdlr.setFormatter(self.__log_fmt)
- logger.addHandler(fhdlr)
- logger.setLevel(level)
- self.__loggers[log_name] = logger
- return self.__loggers[log_name]
- def getLogger(self, log_name = None, bPrint = False, level= logging.DEBUG, ):
- if log_name is None:
- log_name = self.__log_argv['name_default']
- if log_name not in self.__loggers:
- self.__initLog(log_name, level, bPrint)
- return self.__loggers[log_name]
- def mini_log(fn):
- def moniter(*args, **argkv):
- return fn(*args, **argkv)
- logger = CommLogger().getLogger(fn.func_name)
- log_info = {'fn_name' : repr(fn.func_name), 'fn_code' : fn.func_code, 'ctrl' : os.linesep}
- logger.info('The function of %(fn_name)s has been running.%(ctrl)s%(fn_code)s' % log_info)
- return moniter
- @mini_log
- def test():
- print 'test logging module.'
- if __name__ == '__main__':
- cCls = CommLogger()
- log0 = cCls.getLogger()
- log1 = cCls.getLogger('log1', True)
- for i in range(3):
- log0.debug('debug')
- log0.info('info')
- log0.warning('warn')
- log0.error('error')
- log0.critical('critical')
- log1.debug('debug')
- log1.info('info')
- log1.warn('warn')
- log1.error('error')
- log1.critical('critical')
- test()
- print 'end___'