Path: blob/master/venv/Lib/site-packages/pip/_internal/utils/logging.py
811 views
# The following comment should be removed at some point in the future.1# mypy: disallow-untyped-defs=False23from __future__ import absolute_import45import contextlib6import errno7import logging8import logging.handlers9import os10import sys11from logging import Filter, getLogger1213from pip._vendor.six import PY21415from pip._internal.utils.compat import WINDOWS16from pip._internal.utils.deprecation import DEPRECATION_MSG_PREFIX17from pip._internal.utils.misc import ensure_dir1819try:20import threading21except ImportError:22import dummy_threading as threading # type: ignore232425try:26# Use "import as" and set colorama in the else clause to avoid mypy27# errors and get the following correct revealed type for colorama:28# `Union[_importlib_modulespec.ModuleType, None]`29# Otherwise, we get an error like the following in the except block:30# > Incompatible types in assignment (expression has type "None",31# variable has type Module)32# TODO: eliminate the need to use "import as" once mypy addresses some33# of its issues with conditional imports. Here is an umbrella issue:34# https://github.com/python/mypy/issues/129735from pip._vendor import colorama as _colorama36# Lots of different errors can come from this, including SystemError and37# ImportError.38except Exception:39colorama = None40else:41# Import Fore explicitly rather than accessing below as colorama.Fore42# to avoid the following error running mypy:43# > Module has no attribute "Fore"44# TODO: eliminate the need to import Fore once mypy addresses some of its45# issues with conditional imports. This particular case could be an46# instance of the following issue (but also see the umbrella issue above):47# https://github.com/python/mypy/issues/350048from pip._vendor.colorama import Fore4950colorama = _colorama515253_log_state = threading.local()54subprocess_logger = getLogger('pip.subprocessor')555657class BrokenStdoutLoggingError(Exception):58"""59Raised if BrokenPipeError occurs for the stdout stream while logging.60"""61pass626364# BrokenPipeError does not exist in Python 2 and, in addition, manifests65# differently in Windows and non-Windows.66if WINDOWS:67# In Windows, a broken pipe can show up as EINVAL rather than EPIPE:68# https://bugs.python.org/issue1961269# https://bugs.python.org/issue3041870if PY2:71def _is_broken_pipe_error(exc_class, exc):72"""See the docstring for non-Windows Python 3 below."""73return (exc_class is IOError and74exc.errno in (errno.EINVAL, errno.EPIPE))75else:76# In Windows, a broken pipe IOError became OSError in Python 3.77def _is_broken_pipe_error(exc_class, exc):78"""See the docstring for non-Windows Python 3 below."""79return ((exc_class is BrokenPipeError) or # noqa: F82180(exc_class is OSError and81exc.errno in (errno.EINVAL, errno.EPIPE)))82elif PY2:83def _is_broken_pipe_error(exc_class, exc):84"""See the docstring for non-Windows Python 3 below."""85return (exc_class is IOError and exc.errno == errno.EPIPE)86else:87# Then we are in the non-Windows Python 3 case.88def _is_broken_pipe_error(exc_class, exc):89"""90Return whether an exception is a broken pipe error.9192Args:93exc_class: an exception class.94exc: an exception instance.95"""96return (exc_class is BrokenPipeError) # noqa: F821979899@contextlib.contextmanager100def indent_log(num=2):101"""102A context manager which will cause the log output to be indented for any103log messages emitted inside it.104"""105# For thread-safety106_log_state.indentation = get_indentation()107_log_state.indentation += num108try:109yield110finally:111_log_state.indentation -= num112113114def get_indentation():115return getattr(_log_state, 'indentation', 0)116117118class IndentingFormatter(logging.Formatter):119120def __init__(self, *args, **kwargs):121"""122A logging.Formatter that obeys the indent_log() context manager.123124:param add_timestamp: A bool indicating output lines should be prefixed125with their record's timestamp.126"""127self.add_timestamp = kwargs.pop("add_timestamp", False)128super(IndentingFormatter, self).__init__(*args, **kwargs)129130def get_message_start(self, formatted, levelno):131"""132Return the start of the formatted log message (not counting the133prefix to add to each line).134"""135if levelno < logging.WARNING:136return ''137if formatted.startswith(DEPRECATION_MSG_PREFIX):138# Then the message already has a prefix. We don't want it to139# look like "WARNING: DEPRECATION: ...."140return ''141if levelno < logging.ERROR:142return 'WARNING: '143144return 'ERROR: '145146def format(self, record):147"""148Calls the standard formatter, but will indent all of the log message149lines by our current indentation level.150"""151formatted = super(IndentingFormatter, self).format(record)152message_start = self.get_message_start(formatted, record.levelno)153formatted = message_start + formatted154155prefix = ''156if self.add_timestamp:157# TODO: Use Formatter.default_time_format after dropping PY2.158t = self.formatTime(record, "%Y-%m-%dT%H:%M:%S")159prefix = '{t},{record.msecs:03.0f} '.format(**locals())160prefix += " " * get_indentation()161formatted = "".join([162prefix + line163for line in formatted.splitlines(True)164])165return formatted166167168def _color_wrap(*colors):169def wrapped(inp):170return "".join(list(colors) + [inp, colorama.Style.RESET_ALL])171return wrapped172173174class ColorizedStreamHandler(logging.StreamHandler):175176# Don't build up a list of colors if we don't have colorama177if colorama:178COLORS = [179# This needs to be in order from highest logging level to lowest.180(logging.ERROR, _color_wrap(Fore.RED)),181(logging.WARNING, _color_wrap(Fore.YELLOW)),182]183else:184COLORS = []185186def __init__(self, stream=None, no_color=None):187logging.StreamHandler.__init__(self, stream)188self._no_color = no_color189190if WINDOWS and colorama:191self.stream = colorama.AnsiToWin32(self.stream)192193def _using_stdout(self):194"""195Return whether the handler is using sys.stdout.196"""197if WINDOWS and colorama:198# Then self.stream is an AnsiToWin32 object.199return self.stream.wrapped is sys.stdout200201return self.stream is sys.stdout202203def should_color(self):204# Don't colorize things if we do not have colorama or if told not to205if not colorama or self._no_color:206return False207208real_stream = (209self.stream if not isinstance(self.stream, colorama.AnsiToWin32)210else self.stream.wrapped211)212213# If the stream is a tty we should color it214if hasattr(real_stream, "isatty") and real_stream.isatty():215return True216217# If we have an ANSI term we should color it218if os.environ.get("TERM") == "ANSI":219return True220221# If anything else we should not color it222return False223224def format(self, record):225msg = logging.StreamHandler.format(self, record)226227if self.should_color():228for level, color in self.COLORS:229if record.levelno >= level:230msg = color(msg)231break232233return msg234235# The logging module says handleError() can be customized.236def handleError(self, record):237exc_class, exc = sys.exc_info()[:2]238# If a broken pipe occurred while calling write() or flush() on the239# stdout stream in logging's Handler.emit(), then raise our special240# exception so we can handle it in main() instead of logging the241# broken pipe error and continuing.242if (exc_class and self._using_stdout() and243_is_broken_pipe_error(exc_class, exc)):244raise BrokenStdoutLoggingError()245246return super(ColorizedStreamHandler, self).handleError(record)247248249class BetterRotatingFileHandler(logging.handlers.RotatingFileHandler):250251def _open(self):252ensure_dir(os.path.dirname(self.baseFilename))253return logging.handlers.RotatingFileHandler._open(self)254255256class MaxLevelFilter(Filter):257258def __init__(self, level):259self.level = level260261def filter(self, record):262return record.levelno < self.level263264265class ExcludeLoggerFilter(Filter):266267"""268A logging Filter that excludes records from a logger (or its children).269"""270271def filter(self, record):272# The base Filter class allows only records from a logger (or its273# children).274return not super(ExcludeLoggerFilter, self).filter(record)275276277def setup_logging(verbosity, no_color, user_log_file):278"""Configures and sets up all of the logging279280Returns the requested logging level, as its integer value.281"""282283# Determine the level to be logging at.284if verbosity >= 1:285level = "DEBUG"286elif verbosity == -1:287level = "WARNING"288elif verbosity == -2:289level = "ERROR"290elif verbosity <= -3:291level = "CRITICAL"292else:293level = "INFO"294295level_number = getattr(logging, level)296297# The "root" logger should match the "console" level *unless* we also need298# to log to a user log file.299include_user_log = user_log_file is not None300if include_user_log:301additional_log_file = user_log_file302root_level = "DEBUG"303else:304additional_log_file = "/dev/null"305root_level = level306307# Disable any logging besides WARNING unless we have DEBUG level logging308# enabled for vendored libraries.309vendored_log_level = "WARNING" if level in ["INFO", "ERROR"] else "DEBUG"310311# Shorthands for clarity312log_streams = {313"stdout": "ext://sys.stdout",314"stderr": "ext://sys.stderr",315}316handler_classes = {317"stream": "pip._internal.utils.logging.ColorizedStreamHandler",318"file": "pip._internal.utils.logging.BetterRotatingFileHandler",319}320handlers = ["console", "console_errors", "console_subprocess"] + (321["user_log"] if include_user_log else []322)323324logging.config.dictConfig({325"version": 1,326"disable_existing_loggers": False,327"filters": {328"exclude_warnings": {329"()": "pip._internal.utils.logging.MaxLevelFilter",330"level": logging.WARNING,331},332"restrict_to_subprocess": {333"()": "logging.Filter",334"name": subprocess_logger.name,335},336"exclude_subprocess": {337"()": "pip._internal.utils.logging.ExcludeLoggerFilter",338"name": subprocess_logger.name,339},340},341"formatters": {342"indent": {343"()": IndentingFormatter,344"format": "%(message)s",345},346"indent_with_timestamp": {347"()": IndentingFormatter,348"format": "%(message)s",349"add_timestamp": True,350},351},352"handlers": {353"console": {354"level": level,355"class": handler_classes["stream"],356"no_color": no_color,357"stream": log_streams["stdout"],358"filters": ["exclude_subprocess", "exclude_warnings"],359"formatter": "indent",360},361"console_errors": {362"level": "WARNING",363"class": handler_classes["stream"],364"no_color": no_color,365"stream": log_streams["stderr"],366"filters": ["exclude_subprocess"],367"formatter": "indent",368},369# A handler responsible for logging to the console messages370# from the "subprocessor" logger.371"console_subprocess": {372"level": level,373"class": handler_classes["stream"],374"no_color": no_color,375"stream": log_streams["stderr"],376"filters": ["restrict_to_subprocess"],377"formatter": "indent",378},379"user_log": {380"level": "DEBUG",381"class": handler_classes["file"],382"filename": additional_log_file,383"delay": True,384"formatter": "indent_with_timestamp",385},386},387"root": {388"level": root_level,389"handlers": handlers,390},391"loggers": {392"pip._vendor": {393"level": vendored_log_level394}395},396})397398return level_number399400401