Python日志记录顺序多个处理程序

时间:2018-10-31 14:46:33

标签: python logging

我有一个日志处理程序,如果发生严重日志事件,该日志处理程序会将日志文件发送到某个URL,并清除日志文件,因为它已经在其目标位置。 我还使用FileHandler将所有日志写入文件。

我将两个日志都添加到Logger,每个日志都是在其自己的级别上进行的,但是由于在严重事件中发送日志文件仅在将关键消息写入文件中才有意义,因此我需要确保在自定义处理程序之前将FileHandler称为。

我知道我只能添加一个记录器并从FileHandler继承,并在非关键事件时调用父方法,但是我想让该应用程序决定何时该发送日志。 关于如何做到这一点的任何想法?

这是我添加处理程序的方式:

    log = logging.getLogger(__name__)
    log.setLevel(logging.DEBUG)
    log_handler = handlers.TimedRotatingFileHandler(filename=os.path.join(CurrentConfig.LOG_PATH, 'runner.log'), when='d', interval=1, backupCount=3)
    log_handler.setLevel(logging.DEBUG)
    pwx_handler = PwxHandler()
    pwx_handler.setLevel(logging.ERROR)
    formatter = logging.Formatter('[%(asctime)s][%(levelname)s] %(message)s')
    log_handler.setFormatter(formatter)
    log.addHandler(log_handler)
    log.addHandler(pwx_handler)

这是我的自定义处理程序:

from logging import Handler
from glob import glob
from CurrentConfig import CurrentConfig
from datetime import datetime
import requests
from zipfile import ZipFile, ZIP_BZIP2
from os.path import join, basename, splitext
from os import remove
from daemon import Daemon

class PwxHandler(Handler):

    def __init__(self):
        super().__init__()
        self.headers = Daemon().headers

    def emit(self, record):
        super().emit(record)
        logs = glob('/home/guilhon/Projetos/robot-daemon/logs/' + '*.log')
        # logs = glob(CurrentConfig.LOG_PATH + '*.log')
        current_time = datetime.now().strftime('%H_%M_%S')
        zipped_logs = ZipFile(join('/home/guilhon/Projetos/robot-daemon/logs/un', 'zipped_logs_'+current_time+'.zip'), 'w', ZIP_BZIP2)
        # zipped_logs = ZipFile(join(CurrentConfig.LOG_PATH, 'zipped_logs.zip'), 'w', ZIP_BZIP2)
        for log in logs:
            filename = splitext(basename(log))
            zipped_logs.write(log, filename[0] + current_time + filename[1])
        zipped_logs.close()
        # Trunca os arquivos de log
        for log in logs:
            open(log, 'w')
        response = requests.post(CurrentConfig.URL_SERVER + '/robot/log/',
                                 json={'robot_name': CurrentConfig.ROBOT_NAME},
                                 files={'zipped_log': zipped_logs.filename},
                                 verify=CurrentConfig.VERIFY_SSL,
                                 headers=self.headers,
                                 timeout=30)
        if response.status_code == requests.codes.created:
            remove(zipped_logs.filename)

0 个答案:

没有答案