Python基础学习八 写日志

 import logging
from logging import handlers class Logger(object):
level_relations = {
'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARN,
'error': logging.ERROR,
'crit': logging.CRITICAL
} # 日志级别关系映射 def __init__(self, fp, level='debug', when='midnight', interval=1, backCount=5, encoding='utf-8'):
''' :param fp:日志文件路径
:param level: 日志级别 默认是debug
:param when: 分割日志的单位 S 秒、M 分、 H 小时、 D 天、 W 每星期(interval==0时代表星期一)、midnight 每天凌晨
:param interval: 时间间隔 默认每天凌晨
:param backCount: 备份文件个数 默认5个
:param encoding: 日志文件编码
'''
self.level = self.level_relations.get(level)
self.logger = logging.getLogger(fp)
self.logger.setLevel(self.level)
fmt = logging.Formatter('%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s')
sh = logging.StreamHandler()
sh.setFormatter(fmt)
sh.setLevel(self.level)
th = handlers.TimedRotatingFileHandler(fp, when=when, interval=interval, backupCount=backCount,
encoding=encoding)
th.setFormatter(fmt)
th.setLevel(self.level)
self.logger.addHandler(th)
self.logger.addHandler(sh) def debug(self, msg):
self.logger.debug(msg) def info(self, msg):
self.logger.info(msg) def warning(self, msg):
self.logger.warning(msg) def error(self, msg):
self.logger.error(msg) def crit(self, msg):
self.logger.critical(msg) if __name__ == '__main__':
l = Logger('a.log') # 实例化
l.info('hehehe') # 调用
l.debug('哈哈哈')
l.error('xxx')
上一篇:关于ServletConfig的小结


下一篇:python中try except执行顺序