How to reconfigure a logger formatter when using dictConfig

一个人想着一个人 提交于 2019-12-23 18:43:46

问题


I am using dictConfig to setup logging. One of the requirements I have is to change the default converter of the formatter (I am using a single formatter simpleFormatter for all my handlers) to time.gmtime. This would be done like this:

formatter.converter = time.gmtime

If I had access to the formatter. But I don't, so I can not change the default converter. I can think of two ways of doing what I want:

  • pass the relevant parameter via dictConfig, in the formatters section (something like 'converter': 'ext://time.gmtime') But I think this extra parameter is not supported by dictConfig
  • get the formatter after doing a dictConfig and apply the configuration manually: formatter.converter = time.gmtime. I do not know how to get the formatter by name, or whether it is supported or if would be hacking around the logging.config module.

I have found neither examples, nor documentation, nor a way to implement this after taking a look at the source code of the logging module.

Has somebody managed to setup the formatter.converter using a dictConfig setup?


回答1:


Here's an example of how to do it:

import logging
import logging.config
import time

class UTCFormatter(logging.Formatter):
    converter = time.gmtime

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'utc': {
            '()': UTCFormatter,
            'format': '%(asctime)s %(message)s',
        },
        'local': {
            'format': '%(asctime)s %(message)s',
        }
    },
    'handlers': {
        'console1': {
            'class': 'logging.StreamHandler',
            'formatter': 'utc',
        },
        'console2': {
            'class': 'logging.StreamHandler',
            'formatter': 'local',
        },
    },
    'root': {
        'handlers': ['console1', 'console2'],
   }
}

if __name__ == '__main__':
    logging.config.dictConfig(LOGGING)
    logging.warning('Look out!')

When I run the above, I get:

2015-10-17 12:20:36,217 Look out!
2015-10-17 13:20:36,217 Look out!

The use of the '()' key for custom instantiations is documented here in the paragraph beginning All other keys ....



来源:https://stackoverflow.com/questions/33170207/how-to-reconfigure-a-logger-formatter-when-using-dictconfig

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!