gpt4 book ai didi

python - 如何在 python 日志记录配置文件 (logging.conf) 中添加过滤器

转载 作者:太空宇宙 更新时间:2023-11-04 00:38:01 36 4
gpt4 key购买 nike

是否可以在日志配置文件中添加/使用过滤器?比如下面的代码有没有等价的设置?

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))

用于 logging.conf 中的处理程序

[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=format_01
args=(sys.stdout,)

我们可以在配置文件 (logging.conf) 中为上述 python 代码编写日志过滤器作为处理程序吗? (python代码只是举例)

最佳答案

如果你愿意,我在 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')

P.S.:像我知道的那样奇怪我的代码。我截断了一些更复杂的东西。

引用资料:

关于python - 如何在 python 日志记录配置文件 (logging.conf) 中添加过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43062244/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com