]>
Commit | Line | Data |
---|---|---|
53e6db90 DC |
1 | """Top-level module for Flake8. |
2 | ||
3 | This module | |
4 | ||
5 | - initializes logging for the command-line tool | |
6 | - tracks the version of the package | |
7 | - provides a way to configure logging for the command-line tool | |
8 | ||
9 | .. autofunction:: flake8.configure_logging | |
10 | ||
11 | """ | |
12 | from __future__ import annotations | |
13 | ||
14 | import logging | |
15 | import sys | |
16 | ||
17 | LOG = logging.getLogger(__name__) | |
18 | LOG.addHandler(logging.NullHandler()) | |
19 | ||
20 | __version__ = "6.1.0" | |
21 | __version_info__ = tuple(int(i) for i in __version__.split(".") if i.isdigit()) | |
22 | ||
23 | _VERBOSITY_TO_LOG_LEVEL = { | |
24 | # output more than warnings but not debugging info | |
25 | 1: logging.INFO, # INFO is a numerical level of 20 | |
26 | # output debugging information | |
27 | 2: logging.DEBUG, # DEBUG is a numerical level of 10 | |
28 | } | |
29 | ||
30 | LOG_FORMAT = ( | |
31 | "%(name)-25s %(processName)-11s %(relativeCreated)6d " | |
32 | "%(levelname)-8s %(message)s" | |
33 | ) | |
34 | ||
35 | ||
36 | def configure_logging( | |
37 | verbosity: int, | |
38 | filename: str | None = None, | |
39 | logformat: str = LOG_FORMAT, | |
40 | ) -> None: | |
41 | """Configure logging for flake8. | |
42 | ||
43 | :param verbosity: | |
44 | How verbose to be in logging information. | |
45 | :param filename: | |
46 | Name of the file to append log information to. | |
47 | If ``None`` this will log to ``sys.stderr``. | |
48 | If the name is "stdout" or "stderr" this will log to the appropriate | |
49 | stream. | |
50 | """ | |
51 | if verbosity <= 0: | |
52 | return | |
53 | ||
54 | verbosity = min(verbosity, max(_VERBOSITY_TO_LOG_LEVEL)) | |
55 | log_level = _VERBOSITY_TO_LOG_LEVEL[verbosity] | |
56 | ||
57 | if not filename or filename in ("stderr", "stdout"): | |
58 | fileobj = getattr(sys, filename or "stderr") | |
59 | handler_cls: type[logging.Handler] = logging.StreamHandler | |
60 | else: | |
61 | fileobj = filename | |
62 | handler_cls = logging.FileHandler | |
63 | ||
64 | handler = handler_cls(fileobj) | |
65 | handler.setFormatter(logging.Formatter(logformat)) | |
66 | LOG.addHandler(handler) | |
67 | LOG.setLevel(log_level) | |
68 | LOG.debug( | |
69 | "Added a %s logging handler to logger root at %s", filename, __name__ | |
70 | ) |