简体   繁体   中英

python logging dictConfig custom formatter is not being called

i have the following ColoeredFormatter in my Module.

But The Formatter does not get called. I expect "hi" on the console, but i get "This is an info of the root logger".

i've already deleted all.pyc files, but it did not help.

MyModule/__init__.py

from MyModule.ColoredFormatter import ColoredFormatter

__all__ = ('ColoredFormatter')

MyModule/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 ()

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. A shorthand to pass custom arguments to the constructor is to utilise lambda.

Example:

from MyModule import ColoredFormatter

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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