Repository navigation
Expand file tree
/
Copy pathlogger.py
More file actions
444 lines (388 loc) · 13.7 KB
/
Copy pathlogger.py
File metadata and controls
444 lines (388 loc) · 13.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
"""
This module provides a base class `LoggerBase` and a derived class `Logged`
for adding logging capabilities to classes. The `LoggerBase` class expects
a `logger` attribute to be a `logging.Logger` or compatible instance and
provides methods for logging at various levels. The `Logged` class
automatically adds a named logger to the class.
Classes:
LoggerBase:
A base class that adds logging utilities to a class.
Logged:
A derived class that automatically adds a named logger to a class.
Example:
>>> class MyClass(Logged):
... def __init__(self):
... Logged.__init__(self)
>>> my_class = MyClass()
>>> my_class.debug('debug')
>>> my_class.info('info')
>>> my_class.warning('warning')
>>> my_class.error('error')
>>> my_class.exception('exception')
>>> my_class.log(0, 'log')
"""
from __future__ import annotations
import abc
import collections.abc
import logging
import sys
import types
import typing
if typing.TYPE_CHECKING:
import typing_extensions
from . import decorators
__all__ = ['Logged']
#: Accepted values for the logging ``exc_info`` parameter: a bool, an
#: ``(type, value, traceback)`` triple, a bare exception instance, or ``None``.
# From the logging typeshed, converted to be compatible with Python 3.8
# https://github.com/python/typeshed/blob/main/stdlib/logging/__init__.pyi
_ExcInfoType: typing.TypeAlias = (
bool
| tuple[
type[BaseException],
BaseException,
types.TracebackType | None,
]
| tuple[None, None, None]
| BaseException
| None
)
#: Extra frames between ``Logger.exception`` and its caller. Up to Python 3.10
#: ``Logger.exception`` calls ``Logger.error``, and ``logging`` counts that
#: frame against the ``stacklevel``. From Python 3.11 it skips its own frames.
_EXCEPTION_FRAMES: int = int(sys.version_info < (3, 11))
#: Parameter specification capturing a wrapped logger method's arguments.
_P = typing.ParamSpec('_P')
#: Covariant return-type variable for wrapped logger methods.
_T = typing.TypeVar('_T', covariant=True)
class LoggerProtocol(typing.Protocol):
"""Structural type for any ``logging.Logger``-compatible logger.
Objects that provide these methods (such as a ``logging.Logger`` or a
``loguru`` logger) can be used as the ``logger`` attribute of a
``LoggerBase`` subclass. Only the shape matters; no inheritance required.
"""
def debug(
self,
msg: object,
*args: object,
exc_info: _ExcInfoType = None,
stack_info: bool = False,
stacklevel: int = 1,
extra: collections.abc.Mapping[str, object] | None = None,
) -> None:
"""Log ``msg`` at ``DEBUG`` level."""
def info(
self,
msg: object,
*args: object,
exc_info: _ExcInfoType = None,
stack_info: bool = False,
stacklevel: int = 1,
extra: collections.abc.Mapping[str, object] | None = None,
) -> None:
"""Log ``msg`` at ``INFO`` level."""
def warning(
self,
msg: object,
*args: object,
exc_info: _ExcInfoType = None,
stack_info: bool = False,
stacklevel: int = 1,
extra: collections.abc.Mapping[str, object] | None = None,
) -> None:
"""Log ``msg`` at ``WARNING`` level."""
def error(
self,
msg: object,
*args: object,
exc_info: _ExcInfoType = None,
stack_info: bool = False,
stacklevel: int = 1,
extra: collections.abc.Mapping[str, object] | None = None,
) -> None:
"""Log ``msg`` at ``ERROR`` level."""
def critical(
self,
msg: object,
*args: object,
exc_info: _ExcInfoType = None,
stack_info: bool = False,
stacklevel: int = 1,
extra: collections.abc.Mapping[str, object] | None = None,
) -> None:
"""Log ``msg`` at ``CRITICAL`` level."""
def exception(
self,
msg: object,
*args: object,
exc_info: _ExcInfoType = None,
stack_info: bool = False,
stacklevel: int = 1,
extra: collections.abc.Mapping[str, object] | None = None,
) -> None:
"""Log ``msg`` at ``ERROR`` level, including exception information."""
def log(
self,
level: int,
msg: object,
*args: object,
exc_info: _ExcInfoType = None,
stack_info: bool = False,
stacklevel: int = 1,
extra: collections.abc.Mapping[str, object] | None = None,
) -> None:
"""Log ``msg`` at the integer ``level``."""
def _create_instance(
new: collections.abc.Callable[..., _T],
cls: type[_T],
args: tuple[typing.Any, ...],
kwargs: dict[str, typing.Any],
) -> _T:
"""Create an instance with the next ``__new__`` in line.
The constructor arguments are passed on, so that a class which is created
in ``__new__`` gets its value, as ``int`` and ``str`` do. A ``__new__``
that does not take them is called without, the way it always was. That
second call repeats whatever the first one did before it raised.
Args:
new: The next ``__new__`` in the method resolution order.
cls: The class to create an instance of.
args: The positional constructor arguments.
kwargs: The keyword constructor arguments.
Returns:
The new instance.
Raises:
TypeError: When ``new`` accepts the arguments in neither form. The
error is the one for the call with the arguments.
"""
if new is object.__new__:
# `object.__new__` takes no arguments, they are for `__init__`.
return new(cls)
try:
return new(cls, *args, **kwargs)
except TypeError as error:
try:
return new(cls)
except TypeError:
raise error from None
class LoggerBase(abc.ABC):
"""Class which automatically adds logging utilities to your class when
inheriting. Expects `logger` to be a logging.Logger or compatible instance.
Adds easy access to debug, info, warning, error, exception and log methods
>>> class MyClass(LoggerBase):
... logger = logging.getLogger(__name__)
...
... def __init__(self):
... Logged.__init__(self)
>>> my_class = MyClass()
>>> my_class.debug('debug')
>>> my_class.info('info')
>>> my_class.warning('warning')
>>> my_class.error('error')
>>> my_class.exception('exception')
>>> my_class.log(0, 'log')
"""
# I've tried using a protocol to properly type the logger but it gave all
# sorts of issues with mypy so we're using the lazy solution for now. The
# actual classes define the correct type anyway
logger: typing.Any
# logger: LoggerProtocol
@classmethod
def __get_name( # pyright: ignore[reportUnusedFunction]
cls, *name_parts: str
) -> str:
"""Join the non-empty, stripped ``name_parts`` into a dotted name."""
return '.'.join(n.strip() for n in name_parts if n.strip())
@classmethod
def _log_kwargs(
cls,
exc_info: _ExcInfoType,
stack_info: bool,
stacklevel: int,
extra: collections.abc.Mapping[str, object] | None,
) -> dict[str, typing.Any]:
"""Build the keyword arguments that every log method forwards.
Subclasses with a logger that does not take the ``logging`` keyword
arguments can override this method.
Args:
exc_info: Exception information to attach to the record.
stack_info: Whether to attach the current stack to the record.
stacklevel: How many frames up the caller of the log method is.
extra: Extra attributes for the record.
Returns:
The keyword arguments for the method of ``cls.logger``.
"""
return {
'exc_info': exc_info,
'stack_info': stack_info,
# One level more, so the record names the caller of the log
# method instead of the log method itself.
'stacklevel': stacklevel + 1,
'extra': extra,
}
@decorators.wraps_classmethod(logging.Logger.debug)
@classmethod
def debug(
cls,
msg: object,
*args: object,
exc_info: _ExcInfoType = None,
stack_info: bool = False,
stacklevel: int = 1,
extra: collections.abc.Mapping[str, object] | None = None,
) -> None:
"""Log ``msg`` at ``DEBUG`` level on the class logger."""
return cls.logger.debug( # type: ignore[no-any-return]
msg,
*args,
**cls._log_kwargs(exc_info, stack_info, stacklevel, extra),
)
@decorators.wraps_classmethod(logging.Logger.info)
@classmethod
def info(
cls,
msg: object,
*args: object,
exc_info: _ExcInfoType = None,
stack_info: bool = False,
stacklevel: int = 1,
extra: collections.abc.Mapping[str, object] | None = None,
) -> None:
"""Log ``msg`` at ``INFO`` level on the class logger."""
return cls.logger.info( # type: ignore[no-any-return]
msg,
*args,
**cls._log_kwargs(exc_info, stack_info, stacklevel, extra),
)
@decorators.wraps_classmethod(logging.Logger.warning)
@classmethod
def warning(
cls,
msg: object,
*args: object,
exc_info: _ExcInfoType = None,
stack_info: bool = False,
stacklevel: int = 1,
extra: collections.abc.Mapping[str, object] | None = None,
) -> None:
"""Log ``msg`` at ``WARNING`` level on the class logger."""
return cls.logger.warning( # type: ignore[no-any-return]
msg,
*args,
**cls._log_kwargs(exc_info, stack_info, stacklevel, extra),
)
@decorators.wraps_classmethod(logging.Logger.error)
@classmethod
def error(
cls,
msg: object,
*args: object,
exc_info: _ExcInfoType = None,
stack_info: bool = False,
stacklevel: int = 1,
extra: collections.abc.Mapping[str, object] | None = None,
) -> None:
"""Log ``msg`` at ``ERROR`` level on the class logger."""
return cls.logger.error( # type: ignore[no-any-return]
msg,
*args,
**cls._log_kwargs(exc_info, stack_info, stacklevel, extra),
)
@decorators.wraps_classmethod(logging.Logger.critical)
@classmethod
def critical(
cls,
msg: object,
*args: object,
exc_info: _ExcInfoType = None,
stack_info: bool = False,
stacklevel: int = 1,
extra: collections.abc.Mapping[str, object] | None = None,
) -> None:
"""Log ``msg`` at ``CRITICAL`` level on the class logger."""
return cls.logger.critical( # type: ignore[no-any-return]
msg,
*args,
**cls._log_kwargs(exc_info, stack_info, stacklevel, extra),
)
@decorators.wraps_classmethod(logging.Logger.exception)
@classmethod
def exception(
cls,
msg: object,
*args: object,
exc_info: _ExcInfoType = True,
stack_info: bool = False,
stacklevel: int = 1,
extra: collections.abc.Mapping[str, object] | None = None,
) -> None:
"""Log ``msg`` at ``ERROR`` level with exception info attached."""
return cls.logger.exception( # type: ignore[no-any-return]
msg,
*args,
**cls._log_kwargs(
exc_info,
stack_info,
stacklevel + _EXCEPTION_FRAMES,
extra,
),
)
@decorators.wraps_classmethod(logging.Logger.log)
@classmethod
def log(
cls,
level: int,
msg: object,
*args: object,
exc_info: _ExcInfoType = None,
stack_info: bool = False,
stacklevel: int = 1,
extra: collections.abc.Mapping[str, object] | None = None,
) -> None:
"""Log ``msg`` at the integer ``level`` on the class logger."""
return cls.logger.log( # type: ignore[no-any-return]
level,
msg,
*args,
**cls._log_kwargs(exc_info, stack_info, stacklevel, extra),
)
class Logged(LoggerBase):
"""Class which automatically adds a named logger to your class when
inheriting.
Adds easy access to debug, info, warning, error, exception and log methods
>>> class MyClass(Logged):
... def __init__(self):
... Logged.__init__(self)
>>> my_class = MyClass()
>>> my_class.debug('debug')
>>> my_class.info('info')
>>> my_class.warning('warning')
>>> my_class.error('error')
>>> my_class.exception('exception')
>>> my_class.log(0, 'log')
>>> my_class._Logged__get_name('spam')
'spam'
"""
logger: logging.Logger # pragma: no cover
@classmethod
def __get_name(cls, *name_parts: str) -> str:
"""Build the dotted logger name via ``LoggerBase``'s joiner."""
return typing.cast(
str,
LoggerBase._LoggerBase__get_name(*name_parts), # type: ignore[attr-defined] # pyright: ignore[reportUnknownMemberType, reportUnknownVariableType, reportAttributeAccessIssue]
)
def __new__(
cls, *args: typing.Any, **kwargs: typing.Any
) -> typing_extensions.Self:
"""
Create a new instance of the class and initialize the logger.
The logger is named using the module and class name.
Args:
*args: Variable length argument list.
**kwargs: Arbitrary keyword arguments.
Returns:
An instance of the class.
"""
cls.logger = logging.getLogger(
cls.__get_name(cls.__module__, cls.__name__)
)
return _create_instance(super().__new__, cls, args, kwargs)