log_utils.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # log_utils.py -- Logging utilities for Dulwich
  2. # Copyright (C) 2010 Google, Inc.
  3. #
  4. # This program is free software; you can redistribute it and/or
  5. # modify it under the terms of the GNU General Public License
  6. # as published by the Free Software Foundation; either version 2
  7. # of the License, or (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program; if not, write to the Free Software
  16. # Foundation, Inc., 51 Franklin Street, Fifth Floor,
  17. # Boston, MA 02110-1301, USA.
  18. """Logging utilities for Dulwich.
  19. Any module that uses logging needs to do compile-time initialization to set up
  20. the logging environment. Since Dulwich is also used as a library, clients may
  21. not want to see any logging output. In that case, we need to use a special
  22. handler to suppress spurious warnings like "No handlers could be found for
  23. logger dulwich.foo".
  24. For details on the _NullHandler approach, see:
  25. http://docs.python.org/library/logging.html#configuring-logging-for-a-library
  26. For many modules, the only function from the logging module they need is
  27. getLogger; this module exports that function for convenience. If a calling
  28. module needs something else, it can import the standard logging module directly.
  29. """
  30. import logging
  31. import sys
  32. getLogger = logging.getLogger
  33. class _NullHandler(logging.Handler):
  34. """No-op logging handler to avoid unexpected logging warnings."""
  35. def emit(self, record):
  36. pass
  37. _NULL_HANDLER = _NullHandler()
  38. _DULWICH_LOGGER = getLogger('dulwich')
  39. _DULWICH_LOGGER.addHandler(_NULL_HANDLER)
  40. def default_logging_config():
  41. """Set up the default Dulwich loggers."""
  42. remove_null_handler()
  43. logging.basicConfig(level=logging.INFO, stream=sys.stderr,
  44. format='%(asctime)s %(levelname)s: %(message)s')
  45. def remove_null_handler():
  46. """Remove the null handler from the Dulwich loggers.
  47. If a caller wants to set up logging using something other than
  48. default_logging_config, calling this function first is a minor optimization
  49. to avoid the overhead of using the _NullHandler.
  50. """
  51. _DULWICH_LOGGER.removeHandler(_NULL_HANDLER)