logconf.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import logging
  2. import logging.config
  3. import os
  4. import yaml
  5. def log_setup():
  6. """
  7. Set up basic console logging. Root logger level can be set with ROOT_LOG_LEVEL environment variable.
  8. """
  9. # Load the config file
  10. conf_path = os.getenv('LOGGING_CONFIG', None)
  11. if not conf_path:
  12. conf_path = os.path.dirname(__file__) + '/logging.yaml'
  13. with open(conf_path, 'rt') as f:
  14. config = yaml.safe_load(f.read())
  15. # Configure the logging module with the config file
  16. logging.config.dictConfig(config)
  17. install_default_record_field(logging, 'progress', '')
  18. def install_default_record_field(logging, field, value):
  19. """
  20. Wraps the log record factory to add a default progress field value
  21. Required to avoid a KeyError when the progress field is not set
  22. Such as when logging from a different thread
  23. """
  24. old_factory = logging.getLogRecordFactory()
  25. def record_factory(*args, **kwargs):
  26. record = old_factory(*args, **kwargs)
  27. if not hasattr(record, field):
  28. record.progress = value
  29. return record
  30. logging.setLogRecordFactory(record_factory)