【问题标题】:how to add filter in python logging config file (logging.conf)如何在 python 日志配置文件(logging.conf)中添加过滤器
【发布时间】:2017-08-21 02:17:32
【问题描述】:

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

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代码只是举例)

【问题讨论】:

  • logging with filters的可能重复
  • @AbijithMg 这不是重复的,我以这段代码为例。可能是我的问题不清楚。我的问题是,“是否可以在日志配置文件(logging.conf)中使用过滤器作为处理程序”。

标签: python logging


【解决方案1】:

经过搜索,我在官方文档中找到了答案

For example, you cannot configure Filter objects, which provide for filtering of messages beyond simple integer levels, using fileConfig(). If you need to have instances of Filter in your logging configuration, you will need to use dictConfig().

logging.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

【讨论】:

    【解决方案2】:

    如果你愿意,我在 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.:我知道我的代码很奇怪。我截断了一些更复杂的东西。

    参考资料:

    【讨论】:

      猜你喜欢
      • 2014-03-28
      • 1970-01-01
      • 1970-01-01
      • 2018-10-12
      • 2022-01-14
      • 2016-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多