Evaluate statements from within Python logging YAML config file -
consider following snippet of python logging yaml config file:
version: 1 formatters: simple: format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s' handlers: logfile: class: logging.handlers.timedrotatingfilehandler level: debug filename: some_fancy_import_name.generate_filename_called_error backupcount: 5 formatter: simple i load yaml config file way:
with open('logging.yaml', 'r') fd: config = yaml.safe_load(fd.read()) logging.config.dictconfig(config) take special notice of filename handler should write logs. in normal python code, expect some_fancy_import_name.generate_filename_called_errorlog generate string 'error.log'. in all, logging handler should write file 'error.log' in current directory.
however, turns out, not case. when @ current directory, see file named 'some_fancy_import_name.generate_filename_called_errorlog'.
why go through trouble?
i filename programmatically determined. have tried configuring logging using normal python scripting way:
# fancy import name os import environ env # programmatically determine filename path log_location = env.get('openshift_log_dir', '.') log_filename = os.path.join(log_location, 'error') handler = logging.handlers.timedrotatingfilehandler(log_filename) see how log_filename path inferred environment variables.
i translate yaml config file. possible?
perhaps might need dig through dict produced yaml.safe_load(fd.read()) , eval() stuff?
you can add custom constructor , mark value special tag, constructor gets executed when loading it:
import yaml def eval_constructor(loader, node): return eval(loader.construct_scalar(node)) yaml.add_constructor(u'!eval', eval_constructor) some_value = '123' config = yaml.load(""" version: 1 formatters: simple: format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s' handlers: logfile: class: logging.handlers.timedrotatingfilehandler level: debug filename: !eval some_value backupcount: 5 formatter: simple """) print config['handlers']['logfile']['filename'] this prints 123, since value some_value has tag !eval, , therefore loaded eval_constructor.
be aware of security implications of evaling configuration data. arbitrary python code can executed writing yaml file!
Comments
Post a Comment