From 5d29bfa7015088f8ef161e5f6128617644c7ba3a Mon Sep 17 00:00:00 2001 From: Fontrodona Nicolas <nicolas.fontrodona@ens-lyon.fr> Date: Tue, 3 Mar 2020 15:03:13 +0100 Subject: [PATCH] src/logging_conf.py: script containing functions and variables to handle log messages --- src/logging_conf.py | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/src/logging_conf.py b/src/logging_conf.py index 818e5003..9672355b 100644 --- a/src/logging_conf.py +++ b/src/logging_conf.py @@ -7,6 +7,45 @@ 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, @@ -16,6 +55,7 @@ LOGGING_CONFIG = { 'levelname)s - %(message)s' }, "simple": { + '()': 'coloredlogs.ColoredFormatter', 'format': '%(message)s' } }, -- GitLab