pytoolbox.logging module¶
- pytoolbox.logging.setup_logging(name_or_log: str | Logger = '', reset: bool = False, path: Path | str = None, console: bool = False, level: int | str = 10, colorize: bool = False, color_by_level: dict[int | str, str] = None, fmt: str = '%(asctime)s %(levelname)-8s - %(message)s', datefmt: str = '%d/%m/%Y %H:%M:%S') Logger [source]¶
Setup logging.
Example usage
Setup a console output for logger with name test:
>>> log = setup_logging('a', reset=True, console=True, fmt=None, datefmt=None) >>> log.info('this is my info') this is my info >>> log.debug('this is my debug') this is my debug >>> log.setLevel(logging.INFO) >>> log.debug('this is my hidden debug') >>> log.handlers = [] # Remove handlers manually: pas de bras, pas de chocolat ! >>> log.info('no handlers, no messages ;-)')
Colorization is not guaranteed (your environment may disable it). Use pytoolbox.console.toggle_colors appropriately to ensure it.
Colorize (test is disabled because pytest disable colored outputs):
>> log = setup_logging(‘foo’, console=True, colorize=True, fmt=’%(levelname)-8s - %(message)s’) >> log.warning(‘Attention please!’) WARNING - [33mAttention please![0m
Show how to reset handlers of the logger to avoid duplicated messages (e.g. in doctest):
>>> log = setup_logging('test', console=True, fmt=None, datefmt=None) >>> log = setup_logging('test', console=True, fmt=None, datefmt=None) >>> log.info('double message, tu radote pépé') double message, tu radote pépé double message, tu radote pépé
Resetting works as expected:
>>> _ = setup_logging('test', reset=True, console=True, fmt=None, datefmt=None) >>> log.info('single message') single message
Logging to a file instead:
>>> import os, tempfile >>> >>> with tempfile.NamedTemporaryFile('r') as f: ... log = setup_logging('my-logger', path=f.name) ... log.info('Ceci va probablement jamais être lu!') ... lines = f.read().split(os.linesep) ... >>> assert 'INFO - Ceci va probablement jamais être lu!' in lines[0]
- class pytoolbox.logging.ColorizeFilter(*args, **kwargs)[source]¶
Bases:
Filter
- __init__(*args, **kwargs)[source]¶
Initialize a filter.
Initialize with the name of the logger which, together with its children, will have its events allowed through the filter. If no name is specified, allow every event.
- color_by_level = {10: 'cyan', 20: 'white', 30: 'yellow', 40: 'red'}¶