log.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #
  2. # Metrix++, Copyright 2009-2019, Metrix++ Project
  3. # Link: https://github.com/metrixplusplus/metrixplusplus
  4. #
  5. # This file is a part of Metrix++ Tool.
  6. #
  7. import mpp.api
  8. import logging
  9. import os
  10. class Plugin(mpp.api.BasePlugin, mpp.api.IConfigurable):
  11. def declare_configuration(self, parser, default_value='INFO'):
  12. allowed_values = ['DEBUG','INFO','WARNING','ERROR']
  13. default_value_cur = default_value
  14. if '__import__' in os.environ and os.environ['METRIXPLUSPLUS_LOG_LEVEL'] in allowed_values:
  15. default_value_cur = os.environ['METRIXPLUSPLUS_LOG_LEVEL']
  16. parser.add_option("--log-level", "--ll", default=default_value_cur, choices=allowed_values,
  17. help="Defines log level. Possible values are 'DEBUG','INFO','WARNING' or 'ERROR'. "
  18. "Default value is inherited from environment variable 'METRIXPLUSPLUS_LOG_LEVEL' if set. "
  19. "[default: " + default_value + "]")
  20. def configure(self, options):
  21. if options.__dict__['log_level'] == 'ERROR':
  22. log_level = logging.ERROR
  23. elif options.__dict__['log_level'] == 'WARNING':
  24. log_level = logging.WARNING
  25. elif options.__dict__['log_level'] == 'INFO':
  26. log_level = logging.INFO
  27. elif options.__dict__['log_level'] == 'DEBUG':
  28. log_level = logging.DEBUG
  29. else:
  30. raise AssertionError("Unhandled choice of log level")
  31. self.level = log_level
  32. logging.getLogger().setLevel(self.level)
  33. os.environ['METRIXPLUSPLUS_LOG_LEVEL'] = options.__dict__['log_level']
  34. logging.warn("Logging enabled with " + options.__dict__['log_level'] + " level")
  35. def initialize(self):
  36. super(Plugin, self).initialize()
  37. set_default_format()
  38. def set_default_format():
  39. logging.basicConfig(format="[LOG]: %(levelname)s:\t%(message)s", level=logging.WARN)