记录器:未记录DEBUG和INFO(处理程序和级别集)

时间:2017-12-29 12:15:22

标签: python-3.x logging

我想将DEBUG和INFO记录到#!/bin/sh declare -A m_arr cat fruits.txt > /tmp/ID.part while read line do Month=$(echo $line | cut -d, -f1) Fruits=$(echo $line | cut -d, -f2) m_arr[${Month}]=${Fruits} done < /tmp/ID.part for i in ${!m_arr[@]} do echo "$i,${m_arr[$i]}" done ,其余的记录到stdout。我设置了一个过滤器,并创建了一个带有两个不同处理程序的记录器:

stderr

我知道这应该创建一个带有两个不同StreamHandler的记录器,其中一个应该处理DEBUG和INFO。但是,DEBUG和INFO消息记录,而WARNING是:

import logging


# https://stackoverflow.com/questions/16061641/
class InfoFilter(logging.Filter):
    '''Filter used to catch DEBUG and INFO for stdout_handler'''

    def filter(self, rec):
        return rec.levelno in (logging.DEBUG, logging.INFO)


def setup_logger(name):
    formatter = logging.Formatter(
        fmt='%(asctime)s - %(levelname)s - %(module)s - %(message)s'
    )

    stdout_handler = logging.StreamHandler()
    stdout_handler.setLevel(logging.DEBUG)
    stdout_handler.addFilter(InfoFilter())
    stdout_handler.setFormatter(formatter)

    stderr_handler = logging.StreamHandler()
    stderr_handler.setLevel(logging.WARNING)
    stderr_handler.setFormatter(formatter)

    logger = logging.getLogger(name)
    logger.addHandler(stdout_handler)
    logger.addHandler(stderr_handler)

    return logger

0 个答案:

没有答案