logging.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. import contextlib
  2. import errno
  3. import logging
  4. import logging.handlers
  5. import os
  6. import sys
  7. import threading
  8. from dataclasses import dataclass
  9. from io import TextIOWrapper
  10. from logging import Filter
  11. from typing import Any, ClassVar, Generator, List, Optional, TextIO, Type
  12. from pip._vendor.rich.console import (
  13. Console,
  14. ConsoleOptions,
  15. ConsoleRenderable,
  16. RenderableType,
  17. RenderResult,
  18. RichCast,
  19. )
  20. from pip._vendor.rich.highlighter import NullHighlighter
  21. from pip._vendor.rich.logging import RichHandler
  22. from pip._vendor.rich.segment import Segment
  23. from pip._vendor.rich.style import Style
  24. from pip._internal.utils._log import VERBOSE, getLogger
  25. from pip._internal.utils.compat import WINDOWS
  26. from pip._internal.utils.deprecation import DEPRECATION_MSG_PREFIX
  27. from pip._internal.utils.misc import ensure_dir
  28. _log_state = threading.local()
  29. subprocess_logger = getLogger("pip.subprocessor")
  30. class BrokenStdoutLoggingError(Exception):
  31. """
  32. Raised if BrokenPipeError occurs for the stdout stream while logging.
  33. """
  34. def _is_broken_pipe_error(exc_class: Type[BaseException], exc: BaseException) -> bool:
  35. if exc_class is BrokenPipeError:
  36. return True
  37. # On Windows, a broken pipe can show up as EINVAL rather than EPIPE:
  38. # https://bugs.python.org/issue19612
  39. # https://bugs.python.org/issue30418
  40. if not WINDOWS:
  41. return False
  42. return isinstance(exc, OSError) and exc.errno in (errno.EINVAL, errno.EPIPE)
  43. @contextlib.contextmanager
  44. def indent_log(num: int = 2) -> Generator[None, None, None]:
  45. """
  46. A context manager which will cause the log output to be indented for any
  47. log messages emitted inside it.
  48. """
  49. # For thread-safety
  50. _log_state.indentation = get_indentation()
  51. _log_state.indentation += num
  52. try:
  53. yield
  54. finally:
  55. _log_state.indentation -= num
  56. def get_indentation() -> int:
  57. return getattr(_log_state, "indentation", 0)
  58. class IndentingFormatter(logging.Formatter):
  59. default_time_format = "%Y-%m-%dT%H:%M:%S"
  60. def __init__(
  61. self,
  62. *args: Any,
  63. add_timestamp: bool = False,
  64. **kwargs: Any,
  65. ) -> None:
  66. """
  67. A logging.Formatter that obeys the indent_log() context manager.
  68. :param add_timestamp: A bool indicating output lines should be prefixed
  69. with their record's timestamp.
  70. """
  71. self.add_timestamp = add_timestamp
  72. super().__init__(*args, **kwargs)
  73. def get_message_start(self, formatted: str, levelno: int) -> str:
  74. """
  75. Return the start of the formatted log message (not counting the
  76. prefix to add to each line).
  77. """
  78. if levelno < logging.WARNING:
  79. return ""
  80. if formatted.startswith(DEPRECATION_MSG_PREFIX):
  81. # Then the message already has a prefix. We don't want it to
  82. # look like "WARNING: DEPRECATION: ...."
  83. return ""
  84. if levelno < logging.ERROR:
  85. return "WARNING: "
  86. return "ERROR: "
  87. def format(self, record: logging.LogRecord) -> str:
  88. """
  89. Calls the standard formatter, but will indent all of the log message
  90. lines by our current indentation level.
  91. """
  92. formatted = super().format(record)
  93. message_start = self.get_message_start(formatted, record.levelno)
  94. formatted = message_start + formatted
  95. prefix = ""
  96. if self.add_timestamp:
  97. prefix = f"{self.formatTime(record)} "
  98. prefix += " " * get_indentation()
  99. formatted = "".join([prefix + line for line in formatted.splitlines(True)])
  100. return formatted
  101. @dataclass
  102. class IndentedRenderable:
  103. renderable: RenderableType
  104. indent: int
  105. def __rich_console__(
  106. self, console: Console, options: ConsoleOptions
  107. ) -> RenderResult:
  108. segments = console.render(self.renderable, options)
  109. lines = Segment.split_lines(segments)
  110. for line in lines:
  111. yield Segment(" " * self.indent)
  112. yield from line
  113. yield Segment("\n")
  114. class RichPipStreamHandler(RichHandler):
  115. KEYWORDS: ClassVar[Optional[List[str]]] = []
  116. def __init__(self, stream: Optional[TextIO], no_color: bool) -> None:
  117. super().__init__(
  118. console=Console(file=stream, no_color=no_color, soft_wrap=True),
  119. show_time=False,
  120. show_level=False,
  121. show_path=False,
  122. highlighter=NullHighlighter(),
  123. )
  124. # Our custom override on Rich's logger, to make things work as we need them to.
  125. def emit(self, record: logging.LogRecord) -> None:
  126. style: Optional[Style] = None
  127. # If we are given a diagnostic error to present, present it with indentation.
  128. assert isinstance(record.args, tuple)
  129. if record.msg == "[present-rich] %s" and len(record.args) == 1:
  130. rich_renderable = record.args[0]
  131. assert isinstance(
  132. rich_renderable, (ConsoleRenderable, RichCast, str)
  133. ), f"{rich_renderable} is not rich-console-renderable"
  134. renderable: RenderableType = IndentedRenderable(
  135. rich_renderable, indent=get_indentation()
  136. )
  137. else:
  138. message = self.format(record)
  139. renderable = self.render_message(record, message)
  140. if record.levelno is not None:
  141. if record.levelno >= logging.ERROR:
  142. style = Style(color="red")
  143. elif record.levelno >= logging.WARNING:
  144. style = Style(color="yellow")
  145. try:
  146. self.console.print(renderable, overflow="ignore", crop=False, style=style)
  147. except Exception:
  148. self.handleError(record)
  149. def handleError(self, record: logging.LogRecord) -> None:
  150. """Called when logging is unable to log some output."""
  151. exc_class, exc = sys.exc_info()[:2]
  152. # If a broken pipe occurred while calling write() or flush() on the
  153. # stdout stream in logging's Handler.emit(), then raise our special
  154. # exception so we can handle it in main() instead of logging the
  155. # broken pipe error and continuing.
  156. if (
  157. exc_class
  158. and exc
  159. and self.console.file is sys.stdout
  160. and _is_broken_pipe_error(exc_class, exc)
  161. ):
  162. raise BrokenStdoutLoggingError()
  163. return super().handleError(record)
  164. class BetterRotatingFileHandler(logging.handlers.RotatingFileHandler):
  165. def _open(self) -> TextIOWrapper:
  166. ensure_dir(os.path.dirname(self.baseFilename))
  167. return super()._open()
  168. class MaxLevelFilter(Filter):
  169. def __init__(self, level: int) -> None:
  170. self.level = level
  171. def filter(self, record: logging.LogRecord) -> bool:
  172. return record.levelno < self.level
  173. class ExcludeLoggerFilter(Filter):
  174. """
  175. A logging Filter that excludes records from a logger (or its children).
  176. """
  177. def filter(self, record: logging.LogRecord) -> bool:
  178. # The base Filter class allows only records from a logger (or its
  179. # children).
  180. return not super().filter(record)
  181. def setup_logging(verbosity: int, no_color: bool, user_log_file: Optional[str]) -> int:
  182. """Configures and sets up all of the logging
  183. Returns the requested logging level, as its integer value.
  184. """
  185. # Determine the level to be logging at.
  186. if verbosity >= 2:
  187. level_number = logging.DEBUG
  188. elif verbosity == 1:
  189. level_number = VERBOSE
  190. elif verbosity == -1:
  191. level_number = logging.WARNING
  192. elif verbosity == -2:
  193. level_number = logging.ERROR
  194. elif verbosity <= -3:
  195. level_number = logging.CRITICAL
  196. else:
  197. level_number = logging.INFO
  198. level = logging.getLevelName(level_number)
  199. # The "root" logger should match the "console" level *unless* we also need
  200. # to log to a user log file.
  201. include_user_log = user_log_file is not None
  202. if include_user_log:
  203. additional_log_file = user_log_file
  204. root_level = "DEBUG"
  205. else:
  206. additional_log_file = "/dev/null"
  207. root_level = level
  208. # Disable any logging besides WARNING unless we have DEBUG level logging
  209. # enabled for vendored libraries.
  210. vendored_log_level = "WARNING" if level in ["INFO", "ERROR"] else "DEBUG"
  211. # Shorthands for clarity
  212. log_streams = {
  213. "stdout": "ext://sys.stdout",
  214. "stderr": "ext://sys.stderr",
  215. }
  216. handler_classes = {
  217. "stream": "pip._internal.utils.logging.RichPipStreamHandler",
  218. "file": "pip._internal.utils.logging.BetterRotatingFileHandler",
  219. }
  220. handlers = ["console", "console_errors", "console_subprocess"] + (
  221. ["user_log"] if include_user_log else []
  222. )
  223. logging.config.dictConfig(
  224. {
  225. "version": 1,
  226. "disable_existing_loggers": False,
  227. "filters": {
  228. "exclude_warnings": {
  229. "()": "pip._internal.utils.logging.MaxLevelFilter",
  230. "level": logging.WARNING,
  231. },
  232. "restrict_to_subprocess": {
  233. "()": "logging.Filter",
  234. "name": subprocess_logger.name,
  235. },
  236. "exclude_subprocess": {
  237. "()": "pip._internal.utils.logging.ExcludeLoggerFilter",
  238. "name": subprocess_logger.name,
  239. },
  240. },
  241. "formatters": {
  242. "indent": {
  243. "()": IndentingFormatter,
  244. "format": "%(message)s",
  245. },
  246. "indent_with_timestamp": {
  247. "()": IndentingFormatter,
  248. "format": "%(message)s",
  249. "add_timestamp": True,
  250. },
  251. },
  252. "handlers": {
  253. "console": {
  254. "level": level,
  255. "class": handler_classes["stream"],
  256. "no_color": no_color,
  257. "stream": log_streams["stdout"],
  258. "filters": ["exclude_subprocess", "exclude_warnings"],
  259. "formatter": "indent",
  260. },
  261. "console_errors": {
  262. "level": "WARNING",
  263. "class": handler_classes["stream"],
  264. "no_color": no_color,
  265. "stream": log_streams["stderr"],
  266. "filters": ["exclude_subprocess"],
  267. "formatter": "indent",
  268. },
  269. # A handler responsible for logging to the console messages
  270. # from the "subprocessor" logger.
  271. "console_subprocess": {
  272. "level": level,
  273. "class": handler_classes["stream"],
  274. "stream": log_streams["stderr"],
  275. "no_color": no_color,
  276. "filters": ["restrict_to_subprocess"],
  277. "formatter": "indent",
  278. },
  279. "user_log": {
  280. "level": "DEBUG",
  281. "class": handler_classes["file"],
  282. "filename": additional_log_file,
  283. "encoding": "utf-8",
  284. "delay": True,
  285. "formatter": "indent_with_timestamp",
  286. },
  287. },
  288. "root": {
  289. "level": root_level,
  290. "handlers": handlers,
  291. },
  292. "loggers": {"pip._vendor": {"level": vendored_log_level}},
  293. }
  294. )
  295. return level_number