Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hhhrrrttt222111
GitHub Repository: hhhrrrttt222111/Dorkify
Path: blob/master/venv/Lib/site-packages/pip/_internal/utils/logging.py
811 views
1
# The following comment should be removed at some point in the future.
2
# mypy: disallow-untyped-defs=False
3
4
from __future__ import absolute_import
5
6
import contextlib
7
import errno
8
import logging
9
import logging.handlers
10
import os
11
import sys
12
from logging import Filter, getLogger
13
14
from pip._vendor.six import PY2
15
16
from pip._internal.utils.compat import WINDOWS
17
from pip._internal.utils.deprecation import DEPRECATION_MSG_PREFIX
18
from pip._internal.utils.misc import ensure_dir
19
20
try:
21
import threading
22
except ImportError:
23
import dummy_threading as threading # type: ignore
24
25
26
try:
27
# Use "import as" and set colorama in the else clause to avoid mypy
28
# errors and get the following correct revealed type for colorama:
29
# `Union[_importlib_modulespec.ModuleType, None]`
30
# Otherwise, we get an error like the following in the except block:
31
# > Incompatible types in assignment (expression has type "None",
32
# variable has type Module)
33
# TODO: eliminate the need to use "import as" once mypy addresses some
34
# of its issues with conditional imports. Here is an umbrella issue:
35
# https://github.com/python/mypy/issues/1297
36
from pip._vendor import colorama as _colorama
37
# Lots of different errors can come from this, including SystemError and
38
# ImportError.
39
except Exception:
40
colorama = None
41
else:
42
# Import Fore explicitly rather than accessing below as colorama.Fore
43
# to avoid the following error running mypy:
44
# > Module has no attribute "Fore"
45
# TODO: eliminate the need to import Fore once mypy addresses some of its
46
# issues with conditional imports. This particular case could be an
47
# instance of the following issue (but also see the umbrella issue above):
48
# https://github.com/python/mypy/issues/3500
49
from pip._vendor.colorama import Fore
50
51
colorama = _colorama
52
53
54
_log_state = threading.local()
55
subprocess_logger = getLogger('pip.subprocessor')
56
57
58
class BrokenStdoutLoggingError(Exception):
59
"""
60
Raised if BrokenPipeError occurs for the stdout stream while logging.
61
"""
62
pass
63
64
65
# BrokenPipeError does not exist in Python 2 and, in addition, manifests
66
# differently in Windows and non-Windows.
67
if WINDOWS:
68
# In Windows, a broken pipe can show up as EINVAL rather than EPIPE:
69
# https://bugs.python.org/issue19612
70
# https://bugs.python.org/issue30418
71
if PY2:
72
def _is_broken_pipe_error(exc_class, exc):
73
"""See the docstring for non-Windows Python 3 below."""
74
return (exc_class is IOError and
75
exc.errno in (errno.EINVAL, errno.EPIPE))
76
else:
77
# In Windows, a broken pipe IOError became OSError in Python 3.
78
def _is_broken_pipe_error(exc_class, exc):
79
"""See the docstring for non-Windows Python 3 below."""
80
return ((exc_class is BrokenPipeError) or # noqa: F821
81
(exc_class is OSError and
82
exc.errno in (errno.EINVAL, errno.EPIPE)))
83
elif PY2:
84
def _is_broken_pipe_error(exc_class, exc):
85
"""See the docstring for non-Windows Python 3 below."""
86
return (exc_class is IOError and exc.errno == errno.EPIPE)
87
else:
88
# Then we are in the non-Windows Python 3 case.
89
def _is_broken_pipe_error(exc_class, exc):
90
"""
91
Return whether an exception is a broken pipe error.
92
93
Args:
94
exc_class: an exception class.
95
exc: an exception instance.
96
"""
97
return (exc_class is BrokenPipeError) # noqa: F821
98
99
100
@contextlib.contextmanager
101
def indent_log(num=2):
102
"""
103
A context manager which will cause the log output to be indented for any
104
log messages emitted inside it.
105
"""
106
# For thread-safety
107
_log_state.indentation = get_indentation()
108
_log_state.indentation += num
109
try:
110
yield
111
finally:
112
_log_state.indentation -= num
113
114
115
def get_indentation():
116
return getattr(_log_state, 'indentation', 0)
117
118
119
class IndentingFormatter(logging.Formatter):
120
121
def __init__(self, *args, **kwargs):
122
"""
123
A logging.Formatter that obeys the indent_log() context manager.
124
125
:param add_timestamp: A bool indicating output lines should be prefixed
126
with their record's timestamp.
127
"""
128
self.add_timestamp = kwargs.pop("add_timestamp", False)
129
super(IndentingFormatter, self).__init__(*args, **kwargs)
130
131
def get_message_start(self, formatted, levelno):
132
"""
133
Return the start of the formatted log message (not counting the
134
prefix to add to each line).
135
"""
136
if levelno < logging.WARNING:
137
return ''
138
if formatted.startswith(DEPRECATION_MSG_PREFIX):
139
# Then the message already has a prefix. We don't want it to
140
# look like "WARNING: DEPRECATION: ...."
141
return ''
142
if levelno < logging.ERROR:
143
return 'WARNING: '
144
145
return 'ERROR: '
146
147
def format(self, record):
148
"""
149
Calls the standard formatter, but will indent all of the log message
150
lines by our current indentation level.
151
"""
152
formatted = super(IndentingFormatter, self).format(record)
153
message_start = self.get_message_start(formatted, record.levelno)
154
formatted = message_start + formatted
155
156
prefix = ''
157
if self.add_timestamp:
158
# TODO: Use Formatter.default_time_format after dropping PY2.
159
t = self.formatTime(record, "%Y-%m-%dT%H:%M:%S")
160
prefix = '{t},{record.msecs:03.0f} '.format(**locals())
161
prefix += " " * get_indentation()
162
formatted = "".join([
163
prefix + line
164
for line in formatted.splitlines(True)
165
])
166
return formatted
167
168
169
def _color_wrap(*colors):
170
def wrapped(inp):
171
return "".join(list(colors) + [inp, colorama.Style.RESET_ALL])
172
return wrapped
173
174
175
class ColorizedStreamHandler(logging.StreamHandler):
176
177
# Don't build up a list of colors if we don't have colorama
178
if colorama:
179
COLORS = [
180
# This needs to be in order from highest logging level to lowest.
181
(logging.ERROR, _color_wrap(Fore.RED)),
182
(logging.WARNING, _color_wrap(Fore.YELLOW)),
183
]
184
else:
185
COLORS = []
186
187
def __init__(self, stream=None, no_color=None):
188
logging.StreamHandler.__init__(self, stream)
189
self._no_color = no_color
190
191
if WINDOWS and colorama:
192
self.stream = colorama.AnsiToWin32(self.stream)
193
194
def _using_stdout(self):
195
"""
196
Return whether the handler is using sys.stdout.
197
"""
198
if WINDOWS and colorama:
199
# Then self.stream is an AnsiToWin32 object.
200
return self.stream.wrapped is sys.stdout
201
202
return self.stream is sys.stdout
203
204
def should_color(self):
205
# Don't colorize things if we do not have colorama or if told not to
206
if not colorama or self._no_color:
207
return False
208
209
real_stream = (
210
self.stream if not isinstance(self.stream, colorama.AnsiToWin32)
211
else self.stream.wrapped
212
)
213
214
# If the stream is a tty we should color it
215
if hasattr(real_stream, "isatty") and real_stream.isatty():
216
return True
217
218
# If we have an ANSI term we should color it
219
if os.environ.get("TERM") == "ANSI":
220
return True
221
222
# If anything else we should not color it
223
return False
224
225
def format(self, record):
226
msg = logging.StreamHandler.format(self, record)
227
228
if self.should_color():
229
for level, color in self.COLORS:
230
if record.levelno >= level:
231
msg = color(msg)
232
break
233
234
return msg
235
236
# The logging module says handleError() can be customized.
237
def handleError(self, record):
238
exc_class, exc = sys.exc_info()[:2]
239
# If a broken pipe occurred while calling write() or flush() on the
240
# stdout stream in logging's Handler.emit(), then raise our special
241
# exception so we can handle it in main() instead of logging the
242
# broken pipe error and continuing.
243
if (exc_class and self._using_stdout() and
244
_is_broken_pipe_error(exc_class, exc)):
245
raise BrokenStdoutLoggingError()
246
247
return super(ColorizedStreamHandler, self).handleError(record)
248
249
250
class BetterRotatingFileHandler(logging.handlers.RotatingFileHandler):
251
252
def _open(self):
253
ensure_dir(os.path.dirname(self.baseFilename))
254
return logging.handlers.RotatingFileHandler._open(self)
255
256
257
class MaxLevelFilter(Filter):
258
259
def __init__(self, level):
260
self.level = level
261
262
def filter(self, record):
263
return record.levelno < self.level
264
265
266
class ExcludeLoggerFilter(Filter):
267
268
"""
269
A logging Filter that excludes records from a logger (or its children).
270
"""
271
272
def filter(self, record):
273
# The base Filter class allows only records from a logger (or its
274
# children).
275
return not super(ExcludeLoggerFilter, self).filter(record)
276
277
278
def setup_logging(verbosity, no_color, user_log_file):
279
"""Configures and sets up all of the logging
280
281
Returns the requested logging level, as its integer value.
282
"""
283
284
# Determine the level to be logging at.
285
if verbosity >= 1:
286
level = "DEBUG"
287
elif verbosity == -1:
288
level = "WARNING"
289
elif verbosity == -2:
290
level = "ERROR"
291
elif verbosity <= -3:
292
level = "CRITICAL"
293
else:
294
level = "INFO"
295
296
level_number = getattr(logging, level)
297
298
# The "root" logger should match the "console" level *unless* we also need
299
# to log to a user log file.
300
include_user_log = user_log_file is not None
301
if include_user_log:
302
additional_log_file = user_log_file
303
root_level = "DEBUG"
304
else:
305
additional_log_file = "/dev/null"
306
root_level = level
307
308
# Disable any logging besides WARNING unless we have DEBUG level logging
309
# enabled for vendored libraries.
310
vendored_log_level = "WARNING" if level in ["INFO", "ERROR"] else "DEBUG"
311
312
# Shorthands for clarity
313
log_streams = {
314
"stdout": "ext://sys.stdout",
315
"stderr": "ext://sys.stderr",
316
}
317
handler_classes = {
318
"stream": "pip._internal.utils.logging.ColorizedStreamHandler",
319
"file": "pip._internal.utils.logging.BetterRotatingFileHandler",
320
}
321
handlers = ["console", "console_errors", "console_subprocess"] + (
322
["user_log"] if include_user_log else []
323
)
324
325
logging.config.dictConfig({
326
"version": 1,
327
"disable_existing_loggers": False,
328
"filters": {
329
"exclude_warnings": {
330
"()": "pip._internal.utils.logging.MaxLevelFilter",
331
"level": logging.WARNING,
332
},
333
"restrict_to_subprocess": {
334
"()": "logging.Filter",
335
"name": subprocess_logger.name,
336
},
337
"exclude_subprocess": {
338
"()": "pip._internal.utils.logging.ExcludeLoggerFilter",
339
"name": subprocess_logger.name,
340
},
341
},
342
"formatters": {
343
"indent": {
344
"()": IndentingFormatter,
345
"format": "%(message)s",
346
},
347
"indent_with_timestamp": {
348
"()": IndentingFormatter,
349
"format": "%(message)s",
350
"add_timestamp": True,
351
},
352
},
353
"handlers": {
354
"console": {
355
"level": level,
356
"class": handler_classes["stream"],
357
"no_color": no_color,
358
"stream": log_streams["stdout"],
359
"filters": ["exclude_subprocess", "exclude_warnings"],
360
"formatter": "indent",
361
},
362
"console_errors": {
363
"level": "WARNING",
364
"class": handler_classes["stream"],
365
"no_color": no_color,
366
"stream": log_streams["stderr"],
367
"filters": ["exclude_subprocess"],
368
"formatter": "indent",
369
},
370
# A handler responsible for logging to the console messages
371
# from the "subprocessor" logger.
372
"console_subprocess": {
373
"level": level,
374
"class": handler_classes["stream"],
375
"no_color": no_color,
376
"stream": log_streams["stderr"],
377
"filters": ["restrict_to_subprocess"],
378
"formatter": "indent",
379
},
380
"user_log": {
381
"level": "DEBUG",
382
"class": handler_classes["file"],
383
"filename": additional_log_file,
384
"delay": True,
385
"formatter": "indent_with_timestamp",
386
},
387
},
388
"root": {
389
"level": root_level,
390
"handlers": handlers,
391
},
392
"loggers": {
393
"pip._vendor": {
394
"level": vendored_log_level
395
}
396
},
397
})
398
399
return level_number
400
401