日志模块

import os
import logging
import time
from logging import handlers


class Logger():
    level_relations = {
        'debug':logging.DEBUG,
        'info':logging.INFO,
        'warning':logging.WARNING,
        'error':logging.ERROR,
        'crit':logging.CRITICAL
    }#日志级别关系映射
    def __init__(self,level='info',when='D',backCount=3,fmt='%(asctime)s - %(levelname)s: %(message)s'):
        # 获取当前目录
        CURRENT_FOLDER = os.path.split(os.path.realpath(__file__))[0]
        LOG_FOLDER = os.path.join(CURRENT_FOLDER, 'log')
        #LOG_FILE_PATH = os.path.join(LOG_FOLDER, 'log.txt')
        # 获取当前日期
        time_str = time.strftime("%Y-%m-%d")
        #判断文件夹是否存在
        if not os.path.exists(LOG_FOLDER):
            os.mkdir(LOG_FOLDER)
        # 日志文件
        log_file = os.path.join(LOG_FOLDER, "{}.txt".format(time_str))
        self.logger = logging.getLogger(log_file)
        format_str = logging.Formatter(fmt)#设置日志格式
        self.logger.setLevel(self.level_relations.get(level))#设置日志级别
        sh = logging.StreamHandler()#往屏幕上输出
        sh.setFormatter(format_str) #设置屏幕上显示的格式
        th = handlers.TimedRotatingFileHandler(filename=log_file,when=when,backupCount=backCount,encoding='utf-8')#往文件里写入#指定间隔时间自动生成文件的处理器
        th.setFormatter(format_str)#设置文件里写入的格式
        self.logger.addHandler(sh) #把对象加到logger里
        self.logger.addHandler(th)


if __name__ == '__main__':
    """示例代码"""
    # 日期文件对象
    log = Logger(level='debug')
    log.logger.info("输入")
    log.logger.error('异常')
    log.logger.warning("警告")

 

posted @ 2020-11-24 16:33  日天达人  阅读(62)  评论(0编辑  收藏  举报