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,filename,level='info',when='d',back_count=3,fmt='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'):
self.logger = logging.getLogger(filename)
format_str = logging.Formatter(fmt) # 设置日志格式
self.logger.setLevel(self.level_relations.get(level)) # 设置日志级别,需要根据key去字典里取value
sh = logging.StreamHandler()
sh.setFormatter(format_str)
th = handlers.TimedRotatingFileHandler(filename=filename,
when=when,
backupCount=back_count,
encoding='utf-8'
)
th.setFormatter(format_str)
self.logger.addHandler(sh)
self.logger.addHandler(th)


if __name__ == '__main__':
log = Logger('sherry.log')
log.logger.debug('立刻走= like you')
log.logger.info('info=infomation')
log.logger.warning('ssssss=warning')
log.logger.error('error')
原文地址:https://www.cnblogs.com/blackbird0423/p/8543846.html