__init__.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. """Top-level module for Flake8.
  2. This module
  3. - initializes logging for the command-line tool
  4. - tracks the version of the package
  5. - provides a way to configure logging for the command-line tool
  6. .. autofunction:: flake8.configure_logging
  7. """
  8. from __future__ import annotations
  9. import logging
  10. import sys
  11. LOG = logging.getLogger(__name__)
  12. LOG.addHandler(logging.NullHandler())
  13. __version__ = "6.1.0"
  14. __version_info__ = tuple(int(i) for i in __version__.split(".") if i.isdigit())
  15. _VERBOSITY_TO_LOG_LEVEL = {
  16. # output more than warnings but not debugging info
  17. 1: logging.INFO, # INFO is a numerical level of 20
  18. # output debugging information
  19. 2: logging.DEBUG, # DEBUG is a numerical level of 10
  20. }
  21. LOG_FORMAT = (
  22. "%(name)-25s %(processName)-11s %(relativeCreated)6d "
  23. "%(levelname)-8s %(message)s"
  24. )
  25. def configure_logging(
  26. verbosity: int,
  27. filename: str | None = None,
  28. logformat: str = LOG_FORMAT,
  29. ) -> None:
  30. """Configure logging for flake8.
  31. :param verbosity:
  32. How verbose to be in logging information.
  33. :param filename:
  34. Name of the file to append log information to.
  35. If ``None`` this will log to ``sys.stderr``.
  36. If the name is "stdout" or "stderr" this will log to the appropriate
  37. stream.
  38. """
  39. if verbosity <= 0:
  40. return
  41. verbosity = min(verbosity, max(_VERBOSITY_TO_LOG_LEVEL))
  42. log_level = _VERBOSITY_TO_LOG_LEVEL[verbosity]
  43. if not filename or filename in ("stderr", "stdout"):
  44. fileobj = getattr(sys, filename or "stderr")
  45. handler_cls: type[logging.Handler] = logging.StreamHandler
  46. else:
  47. fileobj = filename
  48. handler_cls = logging.FileHandler
  49. handler = handler_cls(fileobj)
  50. handler.setFormatter(logging.Formatter(logformat))
  51. LOG.addHandler(handler)
  52. LOG.setLevel(log_level)
  53. LOG.debug(
  54. "Added a %s logging handler to logger root at %s", filename, __name__
  55. )