日志

添加日志文件和日志流
# -*- coding: utf-8 -*-

import logging
from logging.handlers import TimedRotatingFileHandler

from config import ROOT_PATH


class MyTimedRotatingFileHandler(TimedRotatingFileHandler):

    # 重写rotate方法,解决loggin模块对于多进程写同一个文件的bug
    def rotate(self, source, dest):
        if not callable(self.rotator):

            with open(dest,'w+', encoding='utf-8') as fw:
                with open(source, 'r+', encoding='utf-8') as fr:
                    fw.write(fr.read())
            with open(source, 'w+', encoding='utf-8') as fw:
                fw.write('###\n')

        else:
            self.rotator(source, dest)


def gen_logger(name: str, file_name: str, level=logging.INFO):
    """
    :param name: logger 的名称,
    :param file_name: 日志文件名称
    :param level: 日志等级
    :return: 拥有流和文件记录器的logger
    """
    logger = logging.getLogger(name)  # logger.name

    formatter = logging.Formatter('%(asctime)s %(name)s %(levelname)s: %(message)s')  # 日志的输出格式
    logger.setLevel(level)

    # 日志流(Stream)
    handler = logging.StreamHandler()  # 流记录器
    handler.setFormatter(formatter)  # 设置格式
    logger.addHandler(handler)  # 添加记录器

    # 日志文件(File)
    handler = MyTimedRotatingFileHandler(filename=f'{ROOT_PATH}/logs/{file_name}', when='D', interval=1) # 文件记录器
    handler.setFormatter(formatter)  # 格式
    logger.addHandler(handler)  # 添加记录器

    return logger


# TODO: 根据环境改变日志等级
verify_log = gen_logger('hp_verify', 'hp_verify.log', level=logging.DEBUG)

posted on 2020-10-22 09:55  哎呀!土豆  阅读(70)  评论(0编辑  收藏  举报

导航