|
| 1 | +""" |
| 2 | +Objects to allow logging to handle different string formatters |
| 3 | +Including: |
| 4 | +- Old Style (E.G. '%s', '%(message)s') |
| 5 | +- Brace (E.G. '{0}', '{message}') |
| 6 | +- Dollar (N.E.G.) |
| 7 | +""" |
| 8 | + |
| 9 | +import logging |
| 10 | +from typing import Any |
| 11 | +from string import Template |
| 12 | + |
| 13 | +logger = logging.getLogger(__name__) |
| 14 | + |
| 15 | + |
| 16 | +class FormattedMessage: # pylint: disable=R0903 |
| 17 | + """ |
| 18 | + Base Class for lazily formatting messages for logging |
| 19 | + All formatting logic should be placed in __str__ to allow the logger to discard any unprinted string conversions |
| 20 | + """ |
| 21 | + |
| 22 | + def __init__(self, fmt: str, *args: Any, **kwargs: Any): |
| 23 | + self.fmt = fmt |
| 24 | + self.args = args |
| 25 | + self.kwargs = kwargs |
| 26 | + self._init_warn() |
| 27 | + |
| 28 | + def _init_warn(self) -> None: |
| 29 | + pass |
| 30 | + |
| 31 | + def __str__(self) -> str: |
| 32 | + raise NotImplementedError |
| 33 | + |
| 34 | + |
| 35 | +class BraceMessage(FormattedMessage): # pylint: disable=R0903 |
| 36 | + """ |
| 37 | + Object to allow logging to handle the Brace string formatter '{0}' & '{message}' |
| 38 | + """ |
| 39 | + |
| 40 | + def __str__(self) -> str: |
| 41 | + return self.fmt.format(*self.args, **self.kwargs) |
| 42 | + |
| 43 | + |
| 44 | +class DollarMessage(FormattedMessage): # pylint: disable=R0903 |
| 45 | + """ |
| 46 | + Object to allow logging to handle the Dollar string formatter |
| 47 | + """ |
| 48 | + |
| 49 | + def _init_warn(self) -> None: |
| 50 | + if len(self.args) > 0: |
| 51 | + logger.warning( |
| 52 | + "%s was passed %d positional arguments, which will be ignored", |
| 53 | + self.__class__, |
| 54 | + len(self.args), |
| 55 | + ) |
| 56 | + |
| 57 | + def __str__(self) -> str: |
| 58 | + return Template(self.fmt).substitute(**self.kwargs) |
| 59 | + |
| 60 | + |
| 61 | +class PercentMessage(FormattedMessage): # pylint: disable=R0903 |
| 62 | + """ |
| 63 | + Object to allow logging to handle the Percent formatter '%s' & '%(message)s' |
| 64 | + logging supports this by default; this class is provided for convenience |
| 65 | + """ |
| 66 | + |
| 67 | + def _init_warn(self) -> None: |
| 68 | + if len(self.kwargs) > 0 and len(self.args) > 0: |
| 69 | + logger.warning( |
| 70 | + "%s was passed %d keyword arguments and %d positional arguments," |
| 71 | + " only one can be specified. Defaulting to keyword arguments", |
| 72 | + self.__class__, |
| 73 | + len(self.args), |
| 74 | + len(self.kwargs), |
| 75 | + ) |
| 76 | + |
| 77 | + def __str__(self) -> str: |
| 78 | + fmt_args = self.kwargs if len(self.kwargs) > 0 else self.args |
| 79 | + return self.fmt % fmt_args |
| 80 | + |
| 81 | + |
| 82 | +__all__ = [ |
| 83 | + "FormattedMessage", |
| 84 | + "BraceMessage", |
| 85 | + "DollarMessage", |
| 86 | + "PercentMessage", |
| 87 | +] |
0 commit comments