我不知道如何使用python3.2的这个新属性。在那里,可以使用可调用对象,而不是实现 logging.Filter 类。
- 我正在尝试将dictConfig用于我的记录器(在 python 中)。在那,我想添加一个过滤器,如果记录的消息包含某个短语,它将通过。
- 我知道如何通过实现 logging.Filter 类来做到这一点。
- 但我不知道如何使用 python 3.2 的可调用“花式”属性,如此处所述
好代码在这里
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