Debian Codegraph @

daiquiri/__init__.py

raw symbols SCIP
1 # Licensed under the Apache License, Version 2.0 (the "License"); you may
2 # not use this file except in compliance with the License. You may obtain
3 # a copy of the License at
4 #
5 # http://www.apache.org/licenses/LICENSE-2.0
6 #
7 # Unless required by applicable law or agreed to in writing, software
8 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10 # License for the specific language governing permissions and limitations
11 # under the License.
12 import collections.abc
13 import logging
14 import logging.config
15 import logging.handlers
16 import sys
17 import traceback
18 import types as _ptypes
19 import typing
20
21 from daiquiri import output
22
23 if typing.TYPE_CHECKING:
24 _KeywordArgumentAdapterBase = logging.LoggerAdapter[logging.Logger]
25 else:
26 _KeywordArgumentAdapterBase = logging.LoggerAdapter
27
28
29 class KeywordArgumentAdapter(_KeywordArgumentAdapterBase):
30 """Logger adapter to add keyword arguments to log record's extra data.
31
32 Keywords passed to the log call are added to the "extra"
33 dictionary passed to the underlying logger so they are emitted
34 with the log message and available to the format string.
35
36 Special keywords:
37
38 extra
39 An existing dictionary of extra values to be passed to the
40 logger. If present, the dictionary is copied and extended.
41
42 """
43
44 def process(
45 self, msg: typing.Any, kwargs: "collections.abc.MutableMapping[str, typing.Any]"
46 ) -> typing.Tuple[typing.Any, "collections.abc.MutableMapping[str, typing.Any]"]:
47 # Make a new extra dictionary combining the values we were
48 # given when we were constructed and anything from kwargs.
49 if self.extra is not None:
50 extra = dict(self.extra)
51 if "extra" in kwargs:
52 extra.update(kwargs.pop("extra"))
53 # Move any unknown keyword arguments into the extra
54 # dictionary.
55 for name in list(kwargs.keys()):
56 if name in ("exc_info", "stack_info"):
57 continue
58 extra[name] = kwargs.pop(name)
59 extra["_daiquiri_extra_keys"] = set(extra.keys())
60 kwargs["extra"] = extra
61 return msg, kwargs
62
63
64 def getLogger(
65 name: typing.Optional[str] = None, **kwargs: typing.Any
66 ) -> KeywordArgumentAdapter:
67 """Build a logger with the given name.
68
69 :param name: The name for the logger. This is usually the module
70 name, ``__name__``.
71 :type name: string
72 """
73 return KeywordArgumentAdapter(logging.getLogger(name), kwargs)
74
75
76 def setup(
77 level: typing.Union[int, str] = logging.WARNING,
78 outputs: typing.Iterable[typing.Union[output.Output, str]] = [output.STDERR],
79 program_name: typing.Optional[str] = None,
80 capture_warnings: bool = True,
81 set_excepthook: bool = True,
82 ) -> None:
83 """Set up Python logging.
84
85 This sets up basic handlers for Python logging.
86
87 :param level: Root log level.
88 :param outputs: Iterable of outputs to log to.
89 :param program_name: The name of the program. Auto-detected if not set.
90 :param capture_warnings: Capture warnings from the `warnings` module.
91 """
92 root_logger = logging.getLogger(None)
93
94 # Remove all handlers
95 for handler in list(root_logger.handlers):
96 root_logger.removeHandler(handler)
97
98 # Add configured handlers
99 for out in outputs:
100 if isinstance(out, str):
101 if out not in output.preconfigured:
102 raise RuntimeError("Output {} is not available".format(out))
103 out = output.preconfigured[out]
104
105 out.add_to_logger(root_logger)
106
107 root_logger.setLevel(level)
108
109 if set_excepthook:
110 program_logger = logging.getLogger(program_name)
111
112 initial_excepthook = staticmethod(sys.excepthook)
113
114 def logging_excepthook(
115 exc_type: typing.Type[BaseException],
116 value: BaseException,
117 tb: typing.Optional[_ptypes.TracebackType],
118 ) -> None:
119 program_logger.critical(
120 "".join(traceback.format_exception(exc_type, value, tb))
121 )
122 initial_excepthook(exc_type, value, tb)
123
124 sys.excepthook = logging_excepthook
125
126 if capture_warnings:
127 logging.captureWarnings(True)
128
129
130 def parse_and_set_default_log_levels(
131 default_log_levels: typing.Iterable[str], separator: str = "="
132 ) -> None:
133 """Set default log levels for some loggers.
134
135 :param default_log_levels: List of strings with format
136 <logger_name><separator><log_level>
137 """
138 levels = []
139 for pair in default_log_levels:
140 result = pair.split(separator, 1)
141 if len(result) != 2:
142 raise ValueError("Wrong log level format: `%s`" % result)
143 levels.append(typing.cast(typing.Tuple[str, str], tuple(result)))
144 return set_default_log_levels(levels)
145
146
147 def set_default_log_levels(
148 loggers_and_log_levels: typing.Iterable[
149 typing.Tuple[typing.Optional[str], typing.Union[str, int]]
150 ],
151 ) -> None:
152 """Set default log levels for some loggers.
153
154 :param loggers_and_log_levels: List of tuple (logger name, level).
155 """
156 for logger, level in loggers_and_log_levels:
157 if isinstance(level, str):
158 level = level.upper()
159 logging.getLogger(logger).setLevel(level)