python-3.x - 如何在记录 python 时使用可调用对象作为过滤器

标签 python-3.x logging callable-object

我不知道如何使用这个new property python3.2的。在那里,可以使用可调用对象而不是实现 logging.Filter 类。

  • 我正在尝试使用 dictConfig对于我的记录器(在 python 中)。在那,我想添加一个过滤器,如果记录的消息包含特定短语,它就会通过。
  • 我知道如何通过实现 logging.Filter 类来做到这一点。
  • 但我不知道如何只使用 python 3.2 的可调用“奇特”属性,如所述 here

好的代码在这里

class ignore_progress(logging.Filter):
    def filter(self, record):

        return not ('Progress' in record.getMessage())
class log_progress(logging.Filter):
    def filter(self, record):
        return ('Progress' in record.getMessage())
def contain_progress(record):
    return not ('Progress' in record.message)
logging_dict = {
    "version": 1,
    "disable_existing_loggers": False,  
    "formatters": {
        "standard": {
            "format": "%(asctime)s [%(levelname)s] %(name)s: %(message)s",
        }
    },
    "filters": {
         "ignore_progress": {
            '()': ignore_progress,
        }
    },
    "handlers": {
        "default": {
            "class": "logging.StreamHandler",
            "level": "DEBUG",
            "formatter": "standard",
        },
        "file": {
            "class": "logging.FileHandler",
            "level": "DEBUG",
            "formatter": "standard",
            "filename": 'training_{}.log'.format(str(datetime.date.today())),
            "filters": ["ignore_progress"],
        },
    },
    "loggers": {
        "": {"handlers": ["default", "file"], "level": "DEBUG", "propagate": True, },
    },
}
# Configurate the logger
logging.config.dictConfig(logging_dict)
logger = logging.getLogger(__name__)

logger.info("Run training")
logger.info("Progress.test")

这里有错误的代码

class ignore_progress(logging.Filter):
    def filter(self, record):

        return not ('Progress' in record.getMessage())
class log_progress(logging.Filter):
    def filter(self, record):
        return ('Progress' in record.getMessage())
def contain_progress(record):
    return not ('Progress' in record.message)
logging_dict = {
    "version": 1,
    "disable_existing_loggers": False,  
    "formatters": {
        "standard": {
            "format": "%(asctime)s [%(levelname)s] %(name)s: %(message)s",
        }
    },
    "filters": {
         "ignore_progress": {
            '()': contain_progress,
        }
    },
    "handlers": {
        "default": {
            "class": "logging.StreamHandler",
            "level": "DEBUG",
            "formatter": "standard",
        },
        "file": {
            "class": "logging.FileHandler",
            "level": "DEBUG",
            "formatter": "standard",
            "filename": 'training_{}.log'.format(str(datetime.date.today())),
            "filters": ["ignore_progress"],
        },
    },
    "loggers": {
        "": {"handlers": ["default", "file"], "level": "DEBUG", "propagate": True, },
    },
}
# Configurate the logger
logging.config.dictConfig(logging_dict)
logger = logging.getLogger(__name__)

logger.info("Run training")
logger.info("Progress.test")

上面的错误代码在这个line处有问题在 config.py

最佳答案

当在 dictConfig 中使用 Callable 时,您放入 dictConfig 值中的 Callable 必须是一个 Callable,它返回一个 Callable,如 Python Bug Tracker 中所讨论的:

例如

def my_filter_wrapper():
    # the returned Callable has to accept a single argument (the LogRecord instance passed in this callable) with return value of 1 or 0
    return lambda record: 0 if <your_condition_here> else 1

logging_dict = {
    ...
    'filters': {
         'ignore_progress': {
            '()': my_filter_wrapper,
        }
    },
    ...

如果您的自定义过滤逻辑是单行的并且独立于日志记录实例,则更简单:

logging_dict = {
    ...
    'filters': {
         'ignore_progress': {
            '()': lambda : lambda _: 0 if <your_condition> else 1
        }
    },
    ...

我花了很长时间才弄明白这一点。希望它能帮助任何有同样问题的人。

而且在其 Python 实现中肯定需要一些东西来使其更加优雅。

关于python-3.x - 如何在记录 python 时使用可调用对象作为过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57903344/

相关文章:

node.js - 如何使用 morgan 记录器?

c++ - 将 lambda 函数作为参数传递时没有匹配函数错误

python - 在最小化中使用 CALLABLE 函数时,“numpy.ndarray”对象不可调用

python - 从 python 中的现有字典创建不同的字典

python-3.x - 如何求二叉树中同一层的两个节点之间的水平距离?

python - findall 不返回 Python 3.7 中的所有结果

python - 如何修复 "ValueError: not enough values to unpack (expected 2, got 1)"

logging - 如何将系统日志发送到graylog

Java 应用程序架构 - 需要一个日志记录名称,希望保持类解耦

python - __init__ 和 __call__ 有什么区别?