Skip to content
Snippets Groups Projects
logging_conf.py 2.62 KiB
#!/usr/bin/env python3

# -*- coding: UTF-8 -*-

"""
Description: this file contains a dictionary that allows to \
configure the logging module of python
"""

from typing import Dict, Any
from pathlib import Path
import logging
import logging.config
import coloredlogs


class LoggingLevelError(Exception):
    pass


def logging_def(output: Path, script: str, level: str = "INFO"):
    """
    Define a logging at the current level of the script

    :param output: Folder where the result will be created
    :param script: The name of the script
    :param level: The log level
    """
    possible_levels = ["INFO", "DEBUG", "ERROR", "WARNING", "CRITICAL"]
    if level in possible_levels:
        basename = str(Path(script).name).replace(".py", ".log")
        LOGGING_CONFIG["handlers"]["file"]["filename"] = output / basename
        LOGGING_CONFIG["loggers"][""]["level"] = level
        logging.config.dictConfig(LOGGING_CONFIG)
    elif level != "DISABLE":
        raise LoggingLevelError(f"Logging level unknown : choose from "
                                f"{possible_levels} or DISABLE to disable the "
                                f"initialisation of logging in {__file__}")


coloredlogs.DEFAULT_LEVEL_STYLES = {'critical': {'color': 'red', 'bold': True},
                                    'debug': {'color': 'cyan', 'italic': True,
                                              'bold': True},
                                    'error': {'color': 'red', 'bold': True},
                                    'info': {},
                                    'warning': {'color': 'yellow',
                                                'bold': True}}

LOGGING_CONFIG = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'complex': {
            'format': '%(filename)s:%(lineno)s:%(funcName)s():%(asctime)s - %('
                      'levelname)s - %(message)s'
        },
        "simple": {
           '()': 'coloredlogs.ColoredFormatter',
           'format': '%(message)s'
        }
    },
    'handlers': {
        'default': {
            'level': 'NOTSET',
            'formatter': 'simple',
            'class': 'logging.StreamHandler',
            'stream': 'ext://sys.stdout',  # Default is stderr
        },
        'file': {
            'level': 'NOTSET',
            'formatter': 'complex',
            'class': 'logging.FileHandler',
            'filename': 'test.log',
            'mode': 'w',
        },
    },
    'loggers': {
        '': {  # root logger
            'handlers': ['default', "file"],
            'level': 'NOTSET',
            'propagate': True
        },
    }
}   # type: Dict[str, Any]