logging.py 12 KB

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