Skip to content

Logger

injector.custom_logger.logger.CustomLogger

The class includes all necessary methods to specify a custom logger

Source code in injector/custom_logger/logger.py
 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
class CustomLogger:
    """The class includes all necessary methods to specify a custom logger"""

    loggers: dict = {}

    log_format: str = """{
        "Name":            "name",
        "Levelno":         "levelno",
        "Levelname":       "levelname",
        "Pathname":        "pathname",
        "Filename":        "filename",
        "Module":          "module",
        "Lineno":          "lineno",
        "FuncName":        "funcName",
        "Created":         "created",
        "Asctime":         "asctime",
        "Msecs":           "msecs",
        "RelativeCreated": "relativeCreated",
        "Thread":          "thread",
        "ThreadName":      "threadName",
        "Process":         "process",
        "Message":         "message"
    }"""

    try:
        config: dict = LoadConfig.load_correct_config_dict()
    except Exception as e:
        raise HanaInjectorError(
            "Please, check the error and define the env variable HANA_INJECTOR_CONFIG_FILE_PATH."
        ) from e

    @classmethod
    def _get_logger(cls, name):
        """The method includes a functionality to get the corresponding logger specified by the name

        Args:
            name (any): Specify the corresponding logger name

        Raises:
            HanaInjectorError: Wrapper exception to reformat the forwarded potential exception and include inside the trowed stacktrace

        Returns:
            logger (Logger): Returns the logger
        """

        if cls.loggers.get(name):
            return cls.loggers.get(name)
        else:
            try:
                log_mode: str = cls.config["hana_injector"]["log_mode"]
            except Exception as e:
                raise HanaInjectorError(
                    "Please, check the error and define the error log_mode parameter inside the config file."
                ) from e

            logger = logging.getLogger(name)
            logger.setLevel(CustomLogger._get_log_level_parameter(log_mode))
            logger.propagate = False

            handler = logging.StreamHandler()
            formatter = JsonFormatter(cls.log_format)
            handler.setFormatter(formatter)

            logger.addHandler(handler)
            cls.loggers[name] = logger

            return logger

    @classmethod
    def write_to_console(cls, status, message):
        """The method includes a functionality to write the log messages to the console

        Args:
            status (any): Specify the corresponding status
            message (any): Specify the corresponding message

        Raises:
            HanaInjectorError: Wrapper exception to reformat the forwarded potential exception and include inside the trowed stacktrace
            ValueError: Missed specifying a necessary value

        Returns:
            None
        """

        if cls.config is None:
            raise HanaInjectorError("Can't parse the config yaml. Please, define a valid config yaml") from Exception

        try:
            if cls.config["hana_injector"]["log_mode"] != "debug":
                if status == "error" or status == "warning":
                    CustomLogger._get_correct_status(CustomLogger._get_logger("hana_injector"), status, message)
            else:
                CustomLogger._get_correct_status(CustomLogger._get_logger("hana_injector"), status, message)
        except (KeyError, ValueError):
            raise ValueError("Value not available. Please, set the correct parameter: hana_injector.log_mode")

    @staticmethod
    def _get_correct_status(logger, status, message):
        """The method includes a functionality to find the correct status code

        Args:
            logger (any): Specify the corresponding logger
            status (any): Specify the corresponding status
            message (any): Specify the corresponding message

        Returns:
            None
        """

        if status == "error":
            logger.error(message)
        elif status == "warning":
            logger.warning(message)
        elif status == "information":
            logger.info(message)
        else:
            logger.error("Error, by declaration the right logger status.")

    @staticmethod
    def _get_log_level_parameter(config_log_parameter: str):
        """The method includes a functionality to get the correct log level parameter

        Args:
            config_log_parameter (any): Specify the corresponding configuration log parameter

        Returns:
            log_level_parameter (any): Return the corresponding log level parameter
        """

        if config_log_parameter.lower() == "debug":
            log_level_parameter = logging.DEBUG
        elif config_log_parameter.lower() == "warning":
            log_level_parameter = logging.WARNING
        elif config_log_parameter.lower() == "information":
            log_level_parameter = logging.INFO
        elif config_log_parameter.lower() == "error":
            log_level_parameter = logging.ERROR
        else:
            log_level_parameter = logging.DEBUG

        return log_level_parameter

Functions

write_to_console(status, message) classmethod

The method includes a functionality to write the log messages to the console

Parameters:

Name Type Description Default
status any

Specify the corresponding status

required
message any

Specify the corresponding message

required

Raises:

Type Description
HanaInjectorError

Wrapper exception to reformat the forwarded potential exception and include inside the trowed stacktrace

ValueError

Missed specifying a necessary value

Returns:

Type Description

None

Source code in injector/custom_logger/logger.py
 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
@classmethod
def write_to_console(cls, status, message):
    """The method includes a functionality to write the log messages to the console

    Args:
        status (any): Specify the corresponding status
        message (any): Specify the corresponding message

    Raises:
        HanaInjectorError: Wrapper exception to reformat the forwarded potential exception and include inside the trowed stacktrace
        ValueError: Missed specifying a necessary value

    Returns:
        None
    """

    if cls.config is None:
        raise HanaInjectorError("Can't parse the config yaml. Please, define a valid config yaml") from Exception

    try:
        if cls.config["hana_injector"]["log_mode"] != "debug":
            if status == "error" or status == "warning":
                CustomLogger._get_correct_status(CustomLogger._get_logger("hana_injector"), status, message)
        else:
            CustomLogger._get_correct_status(CustomLogger._get_logger("hana_injector"), status, message)
    except (KeyError, ValueError):
        raise ValueError("Value not available. Please, set the correct parameter: hana_injector.log_mode")