Skip to content

logger_

CoreLogger

A singleton logging class for consistent logging across an application.

Provides the flexibility to initialize with console and rotating file handlers.

Source code in libs\cafex_core\src\cafex_core\logging\logger_.py
 7
 8
 9
10
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
class CoreLogger:
    """A singleton logging class for consistent logging across an application.

    Provides the flexibility to initialize with console and rotating
    file handlers.
    """

    _instance = None

    def __new__(cls, *args, **kwargs):
        """Enforces the singleton pattern.

        Returns:
            SingletonLogger: The single instance of the logging class.
        """
        if not cls._instance:
            cls._instance = super().__new__(cls)
        return cls._instance

    def __init__(self, name, level=logging.INFO):
        """Initializes the logging instance.

        Args:
            name (str, optional): The name of the logging.
            level (int, optional): The logging level. Defaults to logging.INFO.
        """
        self.name = name
        if self.name is not None:
            self.logger = logging.getLogger(self.name)
        else:
            self.logger = logging.getLogger()
        self.logger.setLevel(level)
        self.file_handler = None

    def initialize(self, console_logging, file_path, worker_id="master"):
        """Initializes the logging with console and/or file handlers.

        Args:
            console_logging (bool, optional): Whether to enable console logging.
                Defaults to True.
            file_path (str, optional): The path to the log file. Defaults to "app.log".
            worker_id (str, optional): worker id (gwo, gw1) - master in case of non-parallel.
        """
        if console_logging:
            self._add_console_handler()

        self._add_file_handler(file_path, worker_id)

    def _add_console_handler(self):
        """Adds a console handlers to the logging."""
        console_handler = logging.StreamHandler()
        formatter = logging.Formatter(f"%(asctime)s - %(name)s - %(levelname)s - %(message)s")
        console_handler.setFormatter(formatter)
        self.logger.addHandler(console_handler)

    def _add_file_handler(self, logs_dir, worker_id):
        """Adds a rotating file handlers to the logging.

        Args:
            logs_dir (str): The directory to the log file.
            worker_id (str): worker id ('master' in case of non-parallel)
        """
        timestamp = time.strftime("%Y%m%d%H%M%S")
        _log_file_path = os.path.join(logs_dir, f"{worker_id}_{timestamp}.log")
        self.file_handler = RotatingFileHandler(
            _log_file_path, maxBytes=10 * 1024 * 1024, backupCount=5
        )
        formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
        self.file_handler.setFormatter(formatter)
        self.logger.addHandler(self.file_handler)

    def get_logger(self):
        """Returns the logging instance.

        Returns:
            logging.Logger: The configured logging object.
        """
        return self.logger

__init__(name, level=logging.INFO)

Initializes the logging instance.

Parameters:

Name Type Description Default
name str

The name of the logging.

required
level int

The logging level. Defaults to logging.INFO.

INFO
Source code in libs\cafex_core\src\cafex_core\logging\logger_.py
26
27
28
29
30
31
32
33
34
35
36
37
38
39
def __init__(self, name, level=logging.INFO):
    """Initializes the logging instance.

    Args:
        name (str, optional): The name of the logging.
        level (int, optional): The logging level. Defaults to logging.INFO.
    """
    self.name = name
    if self.name is not None:
        self.logger = logging.getLogger(self.name)
    else:
        self.logger = logging.getLogger()
    self.logger.setLevel(level)
    self.file_handler = None

__new__(*args, **kwargs)

Enforces the singleton pattern.

Returns:

Name Type Description
SingletonLogger

The single instance of the logging class.

Source code in libs\cafex_core\src\cafex_core\logging\logger_.py
16
17
18
19
20
21
22
23
24
def __new__(cls, *args, **kwargs):
    """Enforces the singleton pattern.

    Returns:
        SingletonLogger: The single instance of the logging class.
    """
    if not cls._instance:
        cls._instance = super().__new__(cls)
    return cls._instance

get_logger()

Returns the logging instance.

Returns:

Type Description

logging.Logger: The configured logging object.

Source code in libs\cafex_core\src\cafex_core\logging\logger_.py
78
79
80
81
82
83
84
def get_logger(self):
    """Returns the logging instance.

    Returns:
        logging.Logger: The configured logging object.
    """
    return self.logger

initialize(console_logging, file_path, worker_id='master')

Initializes the logging with console and/or file handlers.

Parameters:

Name Type Description Default
console_logging bool

Whether to enable console logging. Defaults to True.

required
file_path str

The path to the log file. Defaults to "app.log".

required
worker_id str

worker id (gwo, gw1) - master in case of non-parallel.

'master'
Source code in libs\cafex_core\src\cafex_core\logging\logger_.py
41
42
43
44
45
46
47
48
49
50
51
52
53
def initialize(self, console_logging, file_path, worker_id="master"):
    """Initializes the logging with console and/or file handlers.

    Args:
        console_logging (bool, optional): Whether to enable console logging.
            Defaults to True.
        file_path (str, optional): The path to the log file. Defaults to "app.log".
        worker_id (str, optional): worker id (gwo, gw1) - master in case of non-parallel.
    """
    if console_logging:
        self._add_console_handler()

    self._add_file_handler(file_path, worker_id)