log_utils.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. # log_utils.py -- Logging utilities for Dulwich
  2. # Copyright (C) 2010 Google, Inc.
  3. #
  4. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  5. # General Public License as public by the Free Software Foundation; version 2.0
  6. # or (at your option) any later version. You can redistribute it and/or
  7. # modify it under the terms of either of these two licenses.
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. #
  15. # You should have received a copy of the licenses; if not, see
  16. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  17. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  18. # License, Version 2.0.
  19. #
  20. """Logging utilities for Dulwich.
  21. Any module that uses logging needs to do compile-time initialization to set up
  22. the logging environment. Since Dulwich is also used as a library, clients may
  23. not want to see any logging output. In that case, we need to use a special
  24. handler to suppress spurious warnings like "No handlers could be found for
  25. logger dulwich.foo".
  26. For details on the _NullHandler approach, see:
  27. http://docs.python.org/library/logging.html#configuring-logging-for-a-library
  28. For many modules, the only function from the logging module they need is
  29. getLogger; this module exports that function for convenience. If a calling
  30. module needs something else, it can import the standard logging module
  31. directly.
  32. """
  33. import logging
  34. import sys
  35. getLogger = logging.getLogger
  36. class _NullHandler(logging.Handler):
  37. """No-op logging handler to avoid unexpected logging warnings."""
  38. def emit(self, record) -> None:
  39. pass
  40. _NULL_HANDLER = _NullHandler()
  41. _DULWICH_LOGGER = getLogger("dulwich")
  42. _DULWICH_LOGGER.addHandler(_NULL_HANDLER)
  43. def default_logging_config() -> None:
  44. """Set up the default Dulwich loggers."""
  45. remove_null_handler()
  46. logging.basicConfig(
  47. level=logging.INFO,
  48. stream=sys.stderr,
  49. format="%(asctime)s %(levelname)s: %(message)s",
  50. )
  51. def remove_null_handler() -> None:
  52. """Remove the null handler from the Dulwich loggers.
  53. If a caller wants to set up logging using something other than
  54. default_logging_config, calling this function first is a minor optimization
  55. to avoid the overhead of using the _NullHandler.
  56. """
  57. _DULWICH_LOGGER.removeHandler(_NULL_HANDLER)