Skip to content

Commit da48d28

Browse files
committed
use setLoggerClass to define log.verbose
loaded in pip._internals.__init__ must use utils.logging.getLogger to get the right type annotation instead of logging.getLogger, despite no actual difference in behavior
1 parent 9b3e784 commit da48d28

File tree

8 files changed

+60
-26
lines changed

8 files changed

+60
-26
lines changed

src/pip/_internal/__init__.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
from typing import List, Optional
22

33
import pip._internal.utils.inject_securetransport # noqa
4+
from pip._internal.utils import _log
5+
6+
# init_logging() must be called before any call to logging.getLogger()
7+
# which happens at import of most modules.
8+
_log.init_logging()
49

510

611
def main(args=None):

src/pip/_internal/commands/cache.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import logging
21
import os
32
import textwrap
43
from optparse import Values
@@ -8,9 +7,9 @@
87
from pip._internal.cli.base_command import Command
98
from pip._internal.cli.status_codes import ERROR, SUCCESS
109
from pip._internal.exceptions import CommandError, PipError
11-
from pip._internal.utils.logging import VERBOSE
10+
from pip._internal.utils.logging import getLogger
1211

13-
logger = logging.getLogger(__name__)
12+
logger = getLogger(__name__)
1413

1514

1615
class CacheCommand(Command):
@@ -185,7 +184,7 @@ def remove_cache_items(self, options, args):
185184

186185
for filename in files:
187186
os.unlink(filename)
188-
logger.log(VERBOSE, "Removed %s", filename)
187+
logger.verbose("Removed %s", filename)
189188
logger.info("Files removed: %s", len(files))
190189

191190
def purge_cache(self, options, args):

src/pip/_internal/commands/install.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import errno
2-
import logging
32
import operator
43
import os
54
import shutil
@@ -28,7 +27,7 @@
2827
from pip._internal.req.req_tracker import get_requirement_tracker
2928
from pip._internal.utils.distutils_args import parse_distutils_args
3029
from pip._internal.utils.filesystem import test_writable_dir
31-
from pip._internal.utils.logging import VERBOSE
30+
from pip._internal.utils.logging import getLogger
3231
from pip._internal.utils.misc import (
3332
ensure_dir,
3433
get_pip_version,
@@ -43,7 +42,7 @@
4342
should_build_for_install_command,
4443
)
4544

46-
logger = logging.getLogger(__name__)
45+
logger = getLogger(__name__)
4746

4847

4948
def get_check_binary_allowed(format_control):
@@ -236,7 +235,7 @@ def run(self, options, args):
236235

237236
install_options = options.install_options or []
238237

239-
logger.log(VERBOSE, "Using %s", get_pip_version())
238+
logger.verbose("Using %s", get_pip_version())
240239
options.use_user_site = decide_user_install(
241240
options.use_user_site,
242241
prefix_path=options.prefix_path,

src/pip/_internal/network/auth.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,14 @@
44
providing credentials in the context of network requests.
55
"""
66

7-
import logging
87
import urllib.parse
98
from typing import Any, Dict, List, Optional, Tuple
109

1110
from pip._vendor.requests.auth import AuthBase, HTTPBasicAuth
1211
from pip._vendor.requests.models import Request, Response
1312
from pip._vendor.requests.utils import get_netrc_auth
1413

14+
from pip._internal.utils.logging import getLogger
1515
from pip._internal.utils.misc import (
1616
ask,
1717
ask_input,
@@ -21,7 +21,7 @@
2121
)
2222
from pip._internal.vcs.versioncontrol import AuthInfo
2323

24-
logger = logging.getLogger(__name__)
24+
logger = getLogger(__name__)
2525

2626
Credentials = Tuple[str, str, str]
2727

src/pip/_internal/req/req_uninstall.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import csv
22
import functools
3-
import logging
43
import os
54
import sys
65
import sysconfig
@@ -13,7 +12,7 @@
1312
from pip._internal.exceptions import UninstallationError
1413
from pip._internal.locations import get_bin_prefix, get_bin_user
1514
from pip._internal.utils.compat import WINDOWS
16-
from pip._internal.utils.logging import VERBOSE, indent_log
15+
from pip._internal.utils.logging import getLogger, indent_log
1716
from pip._internal.utils.misc import (
1817
ask,
1918
dist_in_usersite,
@@ -26,7 +25,7 @@
2625
)
2726
from pip._internal.utils.temp_dir import AdjacentTempDirectory, TempDirectory
2827

29-
logger = logging.getLogger(__name__)
28+
logger = getLogger(__name__)
3029

3130

3231
def _script_names(dist, script_name, is_gui):
@@ -384,7 +383,7 @@ def remove(self, auto_confirm=False, verbose=False):
384383

385384
for path in sorted(compact(for_rename)):
386385
moved.stash(path)
387-
logger.log(VERBOSE, 'Removing file or directory %s', path)
386+
logger.verbose('Removing file or directory %s', path)
388387

389388
for pth in self.pth.values():
390389
pth.remove()
@@ -599,7 +598,7 @@ def add(self, entry):
599598

600599
def remove(self):
601600
# type: () -> None
602-
logger.log(VERBOSE, 'Removing pth entries from %s:', self.file)
601+
logger.verbose('Removing pth entries from %s:', self.file)
603602

604603
# If the file doesn't exist, log a warning and return
605604
if not os.path.isfile(self.file):
@@ -620,7 +619,7 @@ def remove(self):
620619
lines[-1] = lines[-1] + endline.encode("utf-8")
621620
for entry in self.entries:
622621
try:
623-
logger.log(VERBOSE, 'Removing entry: %s', entry)
622+
logger.verbose('Removing entry: %s', entry)
624623
lines.remove((entry + endline).encode("utf-8"))
625624
except ValueError:
626625
pass

src/pip/_internal/utils/_log.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
"""Customize logging
2+
3+
Defines custom logger class for the `logger.verbose(...)` method.
4+
5+
init_logging() must be called before any other modules that call logging.getLogger.
6+
"""
7+
8+
import logging
9+
from typing import Any, cast
10+
11+
# custom log level for `--verbose` output
12+
# between DEBUG and INFO
13+
VERBOSE = 15
14+
15+
16+
class VerboseLogger(logging.Logger):
17+
"""Custom Logger, defining a verbose log-level
18+
19+
VERBOSE is between INFO and DEBUG.
20+
"""
21+
22+
def verbose(self, msg: str, *args: Any, **kwargs: Any) -> None:
23+
return self.log(VERBOSE, msg, *args, **kwargs)
24+
25+
26+
def getLogger(name: str) -> VerboseLogger:
27+
"""logging.getLogger, but ensures our VerboseLogger class is returned"""
28+
return cast(VerboseLogger, logging.getLogger(name))
29+
30+
31+
def init_logging():
32+
"""Register our VerboseLogger and VERBOSE log level.
33+
34+
Should be called before any calls to getLogger(),
35+
i.e. in pip._internal.__init__
36+
"""
37+
logging.setLoggerClass(VerboseLogger)
38+
logging.addLevelName(VERBOSE, "VERBOSE")

src/pip/_internal/utils/logging.py

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,10 @@
44
import logging.handlers
55
import os
66
import sys
7-
from logging import Filter, getLogger
7+
from logging import Filter
88
from typing import IO, Any, Callable, Iterator, Optional, TextIO, Type, cast
99

10+
from pip._internal.utils._log import VERBOSE, getLogger
1011
from pip._internal.utils.compat import WINDOWS
1112
from pip._internal.utils.deprecation import DEPRECATION_MSG_PREFIX
1213
from pip._internal.utils.misc import ensure_dir
@@ -29,11 +30,6 @@
2930
subprocess_logger = getLogger("pip.subprocessor")
3031

3132

32-
# custom log level for `--verbose` output
33-
# between DEBUG and INFO
34-
VERBOSE = 15
35-
36-
3733
class BrokenStdoutLoggingError(Exception):
3834
"""
3935
Raised if BrokenPipeError occurs for the stdout stream while logging.
@@ -276,7 +272,6 @@ def setup_logging(verbosity, no_color, user_log_file):
276272
Returns the requested logging level, as its integer value.
277273
"""
278274

279-
logging.addLevelName(VERBOSE, "VERBOSE")
280275
# Determine the level to be logging at.
281276
if verbosity >= 2:
282277
level_number = logging.DEBUG

src/pip/_internal/utils/subprocess.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
import os
33
import shlex
44
import subprocess
5-
from functools import partial
65
from typing import Any, Callable, Iterable, List, Mapping, Optional, Union
76

87
from pip._internal.cli.spinners import SpinnerInterface, open_spinner
@@ -145,9 +144,9 @@ def call_subprocess(
145144
log_subprocess = subprocess_logger.info
146145
used_level = logging.INFO
147146
else:
148-
# Then log the subprocess output using DEBUG. This also ensures
147+
# Then log the subprocess output using VERBOSE. This also ensures
149148
# it will be logged to the log file (aka user_log), if enabled.
150-
log_subprocess = partial(subprocess_logger.log, VERBOSE)
149+
log_subprocess = subprocess_logger.verbose
151150
used_level = VERBOSE
152151

153152
# Whether the subprocess will be visible in the console.

0 commit comments

Comments
 (0)