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