问题
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 theformatters
section (something like'converter': 'ext://time.gmtime'
) But I think this extra parameter is not supported bydictConfig
- 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 thelogging.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