是否可以在日志配置文件中添加/使用过滤器?比如下面的代码有没有等效的设置?
import logging
# Set up loggers and handlers.
# ...
class LevelFilter(logging.Filter):
def __init__(self, level):
self.level = level
def filter(self, record):
return record.levelno == self.level
logFileHandler.addFilter(LevelFilter(logging.DEBUG))
用于日志记录中的处理程序。形态
[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=format_01
args=(sys.stdout,)
我们可以在配置文件(logging.conf)中为上面的python代码写日志过滤器作为处理程序吗?(python代码只是举个例子)
经过搜索,我在官方文件中找到了答案,上面写着
例如,您不能使用fileConfig()配置筛选器对象,该对象提供对简单整数级别以外的消息的筛选。如果需要在日志记录配置中包含筛选器实例,则需要使用dictConfig()。
日志记录。conf格式为
[loggers]
keys=root,log02,log03,log04,log05,log06,log07
[handlers]
keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09
[formatters]
keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
下面没有过滤器的配置
[filters]
keys=filter01,filter02
如果你愿意,我在Json做了一个例子。应该很容易切换到您的格式通过以下逻辑:)
{
"version": 1,
"disable_existing_loggers": true,
"filters": {
"skipDebug": {
"()": "__main__.RemoveLevelFilter",
"levelToSkip": "DEBUG"
}
},
"formatters": {
"simple": {
"format": "%(asctime)s|%(name)s [%(levelname)s] - %(message)s"
}
},
"handlers": {
"console":{
"level": "DEBUG",
"class": "logging.StreamHandler",
"formatter": "simple",
"stream" : "ext://sys.stdout"
},
"file": {
"level": "DEBUG",
"class": "logging.handlers.RotatingFileHandler",
"maxBytes": 5242880,
"backupCount": 3,
"formatter": "simple",
"filename": "log.log",
"mode": "a",
"encoding": "utf-8",
"filters": ["skipDebug"]
}
},
"loggers": { },
"root": {
"handlers": ["console", "file"],
"level": "DEBUG"
}
}
当你初始化你的记录器时,比如:
class RemoveLevelFilter(object):
def __init__(self, levelToSkip):
self.level = levelToSkip
def filter(self, record):
return self.getLogLevelName(record.levelno) != self.level
enter code here
def getLogLevelName(self, levelno):
switcher = {
10: "DEBUG",
20: "INFO",
30: "WARNING",
40: "ERROR",
50: "CRITICAL"
}
return switcher.get(levelno, "INVALID")
with open("logging.json", "r", encoding="utf-8") as fd:
logging.config.dictConfig(json.load(fd))
logger = logging.getLogger(__name__)
logger.debug('This is a debug message')
logger.info('This is an info message')
logger.warning('This is a warning message')
logger.error('This is an error message')
logger.critical('This is a critical message')
注:奇怪,我的代码就是这样,我知道。是为了更复杂一点的东西,我删掉了。
参考资料: