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

时间:2017-03-28 06:36:17

标签: python logging

是否可以在记录配置文件中添加/使用过滤器? 例如,以下代码是否有任何等效设置?

MainDashboardBundle

for logging.conf中的处理程序

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)中为上面的python代码编写日志过滤器吗? (例如,python代码)

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

如果您愿意,我在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 .:像我所知道的那样奇怪我的代码。我删节了一些更复杂的东西:) 希望会有所帮助。

参考文献: