using configobj string interpolation and logging.config.dictConfig

Tim Williams tjandacw at cox.net
Tue May 30 08:54:01 EDT 2017


On Friday, May 26, 2017 at 12:26:13 PM UTC-4, Peter Otten wrote:
> Tim Williams wrote:
> 
> > I've spent too much time trying to track this down. I'll just hard-code my
> > filename in my INI file. Maybe I'll get back to it, but I need to move on.
> 
> The only alternative I see would be to build your own InterpolationEngine 
> which understands some kind of escaping so that e. g.
> 
> format = '%%(asctime)s: (%%(levelname)s)  %%(message)s'
> 
> would become
> 
> format = '%(asctime)s: (%(levelname)s)  %(message)s'
> 
> when you invoke the dict() method.

It helps to sometimes just let a problem rest for awhile. I found a workaround to my problem. In my INI file, don't create a 'filename' key in the config['handlers']['file'] section. Set it in my python code after loading the INI file. The following works just fine for me. It doesn't address the issue of config.dict() string interpolating the format key, but it does what I want it to do and that's my bottom line.

Test script:
############
import logging, logging.config, logging.handlers
import configobj

logconfig = configobj.ConfigObj('loggingtest.ini', unrepr=True, raise_errors=True)

config=logconfig['loggng']
config['handlers']['file']['filename'] = logconfig['loggng']['LogFile']
logging.config.dictConfig(config)
formatters = config['formatters']['fmt1']
logger=logging.getLogger('root')
print(config['handlers']['file'])
for h in logger.handlers:
    print('handler {}, stream {}'.format(h.name, h.stream))
############

loggingtest.ini:
###########
[loggng]
version = 1
level = 'INFO'
RootDir = 'TestData'
CaptureDrive = 'C:/'
LogFile = '%(CaptureDrive)s%(RootDir)s/test.log'
	[[formatters]]
		[[[fmt1]]]
			format = '%(asctime)s (%(levelname)s)  %(message)s'
			datefmt =
	[[handlers]]
		[[[console]]]
			class = 'logging.StreamHandler'
			level = 'INFO'
			#stream = 'ext://sys.stdout'
			formatter = 'fmt1'
		[[[file]]]
			class = 'logging.FileHandler'
			level = 'WARN'
			formatter = 'fmt1'	
	[[loggers]]
		[[[root]]]
		level = 'INFO'
		handlers = ['file','console']
###########



More information about the Python-list mailing list