1 import logging 2 from logging import handlers 3 4 5 class Logger(object): 6 level_relations = { 7 'debug': logging.DEBUG, 8 'info': logging.INFO, 9 'warning': logging.WARN, 10 'error': logging.ERROR, 11 'crit': logging.CRITICAL 12 } # 日志级别关系映射 13 14 def __init__(self, fp, level='debug', when='midnight', interval=1, backCount=5, encoding='utf-8'): 15 ''' 16 17 :param fp:日志文件路径 18 :param level: 日志级别 默认是debug 19 :param when: 分割日志的单位 S 秒、M 分、 H 小时、 D 天、 W 每星期(interval==0时代表星期一)、midnight 每天凌晨 20 :param interval: 时间间隔 默认每天凌晨 21 :param backCount: 备份文件个数 默认5个 22 :param encoding: 日志文件编码 23 ''' 24 self.level = self.level_relations.get(level) 25 self.logger = logging.getLogger(fp) 26 self.logger.setLevel(self.level) 27 fmt = logging.Formatter('%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s') 28 sh = logging.StreamHandler() 29 sh.setFormatter(fmt) 30 sh.setLevel(self.level) 31 th = handlers.TimedRotatingFileHandler(fp, when=when, interval=interval, backupCount=backCount, 32 encoding=encoding) 33 th.setFormatter(fmt) 34 th.setLevel(self.level) 35 self.logger.addHandler(th) 36 self.logger.addHandler(sh) 37 38 def debug(self, msg): 39 self.logger.debug(msg) 40 41 def info(self, msg): 42 self.logger.info(msg) 43 44 def warning(self, msg): 45 self.logger.warning(msg) 46 47 def error(self, msg): 48 self.logger.error(msg) 49 50 def crit(self, msg): 51 self.logger.critical(msg) 52 53 54 if __name__ == '__main__': 55 l = Logger('a.log') # 实例化 56 l.info('hehehe') # 调用 57 l.debug('哈哈哈') 58 l.error('xxx')