如何在记录python的过程中使用Callable作为过滤器 [英] How to use a callable as a filter in logging python

查看:43
本文介绍了如何在记录python的过程中使用Callable作为过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如何使用此新属性.在那里,除了实现logging.Filter类之外,还可以使用可调用的类.

I don't know how to use this new property of python3.2. There, instead of implementing logging.Filter class, one can use a callable.

  • 我正在尝试使用 dictConfig 用于我的记录器(在python中).在此,我想添加一个过滤器,以便在记录的消息包含某些短语的情况下通过.
  • 我知道如何通过实现logging.Filter类来做到这一点.
  • 但是我不知道如何仅使用
  • I'm trying to use dictConfig for my logger (in python). In that, I want to add a filter such that it will pass if record's message contains certain phrase.
  • I know how to do that by implementing logging.Filter class.
  • But I don't know how to just use callable 'fancy' property of python 3.2 as stated 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")

上面的错误代码在此 config.py

推荐答案

在dictConfig中使用Callable时,放入dictConfig值中的Callable必须是一个Callable,它返回Python漏洞跟踪器中讨论的Callable:

When using Callable in dictConfig, the Callable you put into the value of dictConfig has to be a Callable which returns a Callable as discussed in the 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,
        }
    },
    ...

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

Or even simpler if your custom filtering logic is a one-liner and independent on the log record instance:

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

我花了很长时间才弄清楚这一点.希望它可以帮助任何有相同问题的人.

It took me a long while to figure this out. Hope it helps anyone has the same questions.

在它的Python实现中肯定需要使它更加优雅的东西.

And there is definitely something needed in its Python implementation to make it more elegant.

这篇关于如何在记录python的过程中使用Callable作为过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆