1
0

logging.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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 PipConsole(Console):
  115. def on_broken_pipe(self) -> None:
  116. # Reraise the original exception, rich 13.8.0+ exits by default
  117. # instead, preventing our handler from firing.
  118. raise BrokenPipeError() from None
  119. class RichPipStreamHandler(RichHandler):
  120. KEYWORDS: ClassVar[Optional[List[str]]] = []
  121. def __init__(self, stream: Optional[TextIO], no_color: bool) -> None:
  122. super().__init__(
  123. console=PipConsole(file=stream, no_color=no_color, soft_wrap=True),
  124. show_time=False,
  125. show_level=False,
  126. show_path=False,
  127. highlighter=NullHighlighter(),
  128. )
  129. # Our custom override on Rich's logger, to make things work as we need them to.
  130. def emit(self, record: logging.LogRecord) -> None:
  131. style: Optional[Style] = None
  132. # If we are given a diagnostic error to present, present it with indentation.
  133. if getattr(record, "rich", False):
  134. assert isinstance(record.args, tuple)
  135. (rich_renderable,) = record.args
  136. assert isinstance(
  137. rich_renderable, (ConsoleRenderable, RichCast, str)
  138. ), f"{rich_renderable} is not rich-console-renderable"
  139. renderable: RenderableType = IndentedRenderable(
  140. rich_renderable, indent=get_indentation()
  141. )
  142. else:
  143. message = self.format(record)
  144. renderable = self.render_message(record, message)
  145. if record.levelno is not None:
  146. if record.levelno >= logging.ERROR:
  147. style = Style(color="red")
  148. elif record.levelno >= logging.WARNING:
  149. style = Style(color="yellow")
  150. try:
  151. self.console.print(renderable, overflow="ignore", crop=False, style=style)
  152. except Exception:
  153. self.handleError(record)
  154. def handleError(self, record: logging.LogRecord) -> None:
  155. """Called when logging is unable to log some output."""
  156. exc_class, exc = sys.exc_info()[:2]
  157. # If a broken pipe occurred while calling write() or flush() on the
  158. # stdout stream in logging's Handler.emit(), then raise our special
  159. # exception so we can handle it in main() instead of logging the
  160. # broken pipe error and continuing.
  161. if (
  162. exc_class
  163. and exc
  164. and self.console.file is sys.stdout
  165. and _is_broken_pipe_error(exc_class, exc)
  166. ):
  167. raise BrokenStdoutLoggingError()
  168. return super().handleError(record)
  169. class BetterRotatingFileHandler(logging.handlers.RotatingFileHandler):
  170. def _open(self) -> TextIOWrapper:
  171. ensure_dir(os.path.dirname(self.baseFilename))
  172. return super()._open()
  173. class MaxLevelFilter(Filter):
  174. def __init__(self, level: int) -> None:
  175. self.level = level
  176. def filter(self, record: logging.LogRecord) -> bool:
  177. return record.levelno < self.level
  178. class ExcludeLoggerFilter(Filter):
  179. """
  180. A logging Filter that excludes records from a logger (or its children).
  181. """
  182. def filter(self, record: logging.LogRecord) -> bool:
  183. # The base Filter class allows only records from a logger (or its
  184. # children).
  185. return not super().filter(record)
  186. def setup_logging(verbosity: int, no_color: bool, user_log_file: Optional[str]) -> int:
  187. """Configures and sets up all of the logging
  188. Returns the requested logging level, as its integer value.
  189. """
  190. # Determine the level to be logging at.
  191. if verbosity >= 2:
  192. level_number = logging.DEBUG
  193. elif verbosity == 1:
  194. level_number = VERBOSE
  195. elif verbosity == -1:
  196. level_number = logging.WARNING
  197. elif verbosity == -2:
  198. level_number = logging.ERROR
  199. elif verbosity <= -3:
  200. level_number = logging.CRITICAL
  201. else:
  202. level_number = logging.INFO
  203. level = logging.getLevelName(level_number)
  204. # The "root" logger should match the "console" level *unless* we also need
  205. # to log to a user log file.
  206. include_user_log = user_log_file is not None
  207. if include_user_log:
  208. additional_log_file = user_log_file
  209. root_level = "DEBUG"
  210. else:
  211. additional_log_file = "/dev/null"
  212. root_level = level
  213. # Disable any logging besides WARNING unless we have DEBUG level logging
  214. # enabled for vendored libraries.
  215. vendored_log_level = "WARNING" if level in ["INFO", "ERROR"] else "DEBUG"
  216. # Shorthands for clarity
  217. log_streams = {
  218. "stdout": "ext://sys.stdout",
  219. "stderr": "ext://sys.stderr",
  220. }
  221. handler_classes = {
  222. "stream": "pip._internal.utils.logging.RichPipStreamHandler",
  223. "file": "pip._internal.utils.logging.BetterRotatingFileHandler",
  224. }
  225. handlers = ["console", "console_errors", "console_subprocess"] + (
  226. ["user_log"] if include_user_log else []
  227. )
  228. logging.config.dictConfig(
  229. {
  230. "version": 1,
  231. "disable_existing_loggers": False,
  232. "filters": {
  233. "exclude_warnings": {
  234. "()": "pip._internal.utils.logging.MaxLevelFilter",
  235. "level": logging.WARNING,
  236. },
  237. "restrict_to_subprocess": {
  238. "()": "logging.Filter",
  239. "name": subprocess_logger.name,
  240. },
  241. "exclude_subprocess": {
  242. "()": "pip._internal.utils.logging.ExcludeLoggerFilter",
  243. "name": subprocess_logger.name,
  244. },
  245. },
  246. "formatters": {
  247. "indent": {
  248. "()": IndentingFormatter,
  249. "format": "%(message)s",
  250. },
  251. "indent_with_timestamp": {
  252. "()": IndentingFormatter,
  253. "format": "%(message)s",
  254. "add_timestamp": True,
  255. },
  256. },
  257. "handlers": {
  258. "console": {
  259. "level": level,
  260. "class": handler_classes["stream"],
  261. "no_color": no_color,
  262. "stream": log_streams["stdout"],
  263. "filters": ["exclude_subprocess", "exclude_warnings"],
  264. "formatter": "indent",
  265. },
  266. "console_errors": {
  267. "level": "WARNING",
  268. "class": handler_classes["stream"],
  269. "no_color": no_color,
  270. "stream": log_streams["stderr"],
  271. "filters": ["exclude_subprocess"],
  272. "formatter": "indent",
  273. },
  274. # A handler responsible for logging to the console messages
  275. # from the "subprocessor" logger.
  276. "console_subprocess": {
  277. "level": level,
  278. "class": handler_classes["stream"],
  279. "stream": log_streams["stderr"],
  280. "no_color": no_color,
  281. "filters": ["restrict_to_subprocess"],
  282. "formatter": "indent",
  283. },
  284. "user_log": {
  285. "level": "DEBUG",
  286. "class": handler_classes["file"],
  287. "filename": additional_log_file,
  288. "encoding": "utf-8",
  289. "delay": True,
  290. "formatter": "indent_with_timestamp",
  291. },
  292. },
  293. "root": {
  294. "level": root_level,
  295. "handlers": handlers,
  296. },
  297. "loggers": {"pip._vendor": {"level": vendored_log_level}},
  298. }
  299. )
  300. return level_number