2
0

__init__.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. """Library setup."""
  2. import logging
  3. # Current version of the library
  4. __version__ = '0.1.1'
  5. def get_version():
  6. """
  7. Return a string with the current version of the library.
  8. :rtype: ``string``
  9. :return: Library version (e.g., "0.1.0").
  10. """
  11. return __version__
  12. def init_logging():
  13. """
  14. Initialize logging for testing.
  15. Temporary workaround for build timeouts by enabling logging to
  16. stdout so that Travis doesn't think the build has hung.
  17. """
  18. set_stream_logger(__name__, level=logging.DEBUG)
  19. class NullHandler(logging.Handler):
  20. """A null handler for the logger."""
  21. def emit(self, record):
  22. """Don't emit a log."""
  23. pass
  24. # By default, do not force any logging by the library. If you want to see the
  25. # log messages in your scripts, add the following to the top of your script:
  26. # import cloudbridge
  27. # cloudbridge.set_stream_logger(__name__)
  28. # OR
  29. # cloudbridge.set_file_logger(__name__, '/tmp/cb.log')
  30. default_format_string = "%(asctime)s [%(levelname)s] %(name)s: %(message)s"
  31. log = logging.getLogger('cloudbridge')
  32. log.addHandler(NullHandler())
  33. # Convenience functions to set logging to a particular file or stream
  34. # To enable either of these by default within CloudBridge, add the following
  35. # at the top of a CloudBridge module:
  36. # import cloudbridge
  37. # cloudbridge.set_stream_logger(__name__)
  38. # OR
  39. # cloudbridge.set_file_logger(__name__, '/tmp/cb.log')
  40. def set_stream_logger(name, level=logging.DEBUG, format_string=None):
  41. """A convenience method to set the global logger to stream."""
  42. global log
  43. if not format_string:
  44. format_string = default_format_string
  45. logger = logging.getLogger(name)
  46. logger.setLevel(level)
  47. fh = logging.StreamHandler()
  48. fh.setLevel(level)
  49. formatter = logging.Formatter(format_string)
  50. fh.setFormatter(formatter)
  51. logger.addHandler(fh)
  52. log = logger
  53. def set_file_logger(name, filepath, level=logging.INFO, format_string=None):
  54. """A convenience method to set the global logger to a file."""
  55. global log
  56. if not format_string:
  57. format_string = default_format_string
  58. logger = logging.getLogger(name)
  59. logger.setLevel(level)
  60. fh = logging.FileHandler(filepath)
  61. fh.setLevel(level)
  62. formatter = logging.Formatter(format_string)
  63. fh.setFormatter(formatter)
  64. logger.addHandler(fh)
  65. log = logger