简体   繁体   English

python 未调用记录 dictConfig 自定义格式化程序

[英]python logging dictConfig custom formatter is not being called

i have the following ColoeredFormatter in my Module.我的模块中有以下 ColoeredFormatter。

But The Formatter does not get called.但是 The Formatter 不会被调用。 I expect "hi" on the console, but i get "This is an info of the root logger".我希望在控制台上显示“hi”,但我得到“这是根记录器的信息”。

i've already deleted all.pyc files, but it did not help.我已经删除了 all.pyc 文件,但没有帮助。

MyModule/__init__.py我的模块/__init__.py

from MyModule.ColoredFormatter import ColoredFormatter

__all__ = ('ColoredFormatter')

MyModule/ColoredFormatter.py我的模块/ColoredFormatter.py

import logging

class ColoredFormatter(logging.Formatter):
    def __init__(self, default):
        self.default = default

    def format(self, record):
        print("hi")
        record.msg = "hi"
        return self.default.format(record)

My Script我的剧本

import logging, logging.config, yaml

conf="""
logging:
  version: 1
  disable_existing_loggers: true
  root:
    level: !!python/name:logging.NOTSET
    handlers: [console]
  handlers:
    console:
      class: logging.StreamHandler
      stream: ext://sys.stdout
      formatter: myFormatter
      level: !!python/name:logging.NOTSET

  formatters:
    myFormatter:
      class: !!python/name:MyModule.ColoredFormatter
"""
dict = yaml.parse(conf)
logging.config.dictConfig(dict["logging"])

logging.info("This is an info of the root logger")

in the formatter section i had to replace class by () 在格式化程序部分我不得不用()替换class

import logging, logging.config, yaml

conf="""
logging:
  version: 1
  disable_existing_loggers: true
  root:
    level: !!python/name:logging.NOTSET
    handlers: [console]
  handlers:
    console:
      class: logging.StreamHandler
      stream: ext://sys.stdout
      formatter: myFormatter
      level: !!python/name:logging.NOTSET

  formatters:
    myFormatter:
      '()': MyModule.ColoredFormatter
"""
dict = yaml.parse(conf)
logging.config.dictConfig(dict["logging"])

logging.info("This is an info of the root logger")

I'd like to add that the callable accepts a factory in dictConfig.我想补充一点,可调用对象接受dictConfig. A shorthand to pass custom arguments to the constructor is to utilise lambda.将自定义 arguments 传递给构造函数的简写是使用 lambda。

Example:例子:

from MyModule import ColoredFormatter

...
    'formatters':
        '()': lambda: ColoredFormatter(foo='bar', ...),

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM