Module robotic_manipulator_rloa.utils.logger

Expand source code
import logging
from datetime import datetime
from logging import LogRecord
from logging.config import dictConfig
from logging.handlers import RotatingFileHandler


class Logger:  # pylint: disable=too-many-instance-attributes
    """ Stores and processes the logs """

    @staticmethod
    def set_logger_setup() -> None:
        """
        Sets the logger setup with a predefined configuration.
        """

        log_config_dict = Logger.generate_logging_config_dict()
        dictConfig(log_config_dict)
        rotating_file_handler = RotatingFileHandler(filename='training_logs.log', mode='a', maxBytes=50000000,
                                                    backupCount=10, encoding='utf-8')
        rotating_file_handler.setFormatter(logging.Formatter(
            '"%(levelname)s"|"{datetime}"|%(message)s'.format(datetime=datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%fZ'))
        ))
        rotating_file_handler.setLevel(logging.INFO)
        logger = get_global_logger()
        logger.addHandler(rotating_file_handler)
        logger.setLevel(20)

    @staticmethod
    def generate_logging_config_dict() -> dict:
        """
        Generates the configuration dictionary that is used to configure the logger.
        Returns:
            Configuration dictionary.
        """
        return {
            'version': 1,
            'disable_existing_loggers': False,
            'formatters': {
                'custom_formatter': {
                    '()': CustomFormatter,
                    'dateformat': '%Y-%m-%dT%H:%M:%S.%06d%z'
                },
            },
            'handlers': {
                'debug_console_handler': {
                    'level': 'NOTSET',
                    'formatter': 'custom_formatter',
                    'class': 'logging.StreamHandler',
                    'stream': 'ext://sys.stdout',
                }
            },
            'loggers': {
                '': {
                    'handlers': ['debug_console_handler'],
                    'level': 'NOTSET',
                },
            }
        }


def get_global_logger() -> logging.Logger:
    """
    Getter for the logger.
    Returns:
        Logger instance to be used on the framework.
    """
    return logging.getLogger(__name__)


class CustomFormatter(logging.Formatter):

    def __init__(self, dateformat: str = None):
        """
        CustomFormatter for the logger.
        """
        super().__init__()
        self.dateformat = dateformat

    def format(self, record: LogRecord) -> str:
        """
        Formats the provided LogRecord instance.
        Returns:
            Formatted LogRecord as string.
        """
        # Set format and colors
        grey = "\033[38;20m"
        green = "\033[32;20m"
        yellow = "\033[33;20m"
        red = "\033[31;20m"
        bold_red = "\033[31;1m"
        reset = "\033[0m"
        format_ = '[%(levelname)-8s] - {datetime} - %(message)s'.format(
            datetime=datetime.now().astimezone().strftime('%Y-%m-%dT%H:%M:%S.%f%z')
        )

        self.FORMATS = {
            logging.DEBUG: green + format_ + reset,
            logging.INFO: grey + format_ + reset,
            logging.WARNING: yellow + format_ + reset,
            logging.ERROR: red + format_ + reset,
            logging.CRITICAL: bold_red + format_ + reset
        }

        log_format = self.FORMATS.get(record.levelno)

        formatter = logging.Formatter(log_format, datefmt=self.dateformat)
        return formatter.format(record)

Functions

def get_global_logger() ‑> logging.Logger

Getter for the logger.

Returns

Logger instance to be used on the framework.

Expand source code
def get_global_logger() -> logging.Logger:
    """
    Getter for the logger.
    Returns:
        Logger instance to be used on the framework.
    """
    return logging.getLogger(__name__)

Classes

class CustomFormatter (dateformat: str = None)

Formatter instances are used to convert a LogRecord to text.

Formatters need to know how a LogRecord is constructed. They are responsible for converting a LogRecord to (usually) a string which can be interpreted by either a human or an external system. The base Formatter allows a formatting string to be specified. If none is supplied, the style-dependent default value, "%(message)s", "{message}", or "${message}", is used.

The Formatter can be initialized with a format string which makes use of knowledge of the LogRecord attributes - e.g. the default value mentioned above makes use of the fact that the user's message and arguments are pre- formatted into a LogRecord's message attribute. Currently, the useful attributes in a LogRecord are described by:

%(name)s Name of the logger (logging channel) %(levelno)s Numeric logging level for the message (DEBUG, INFO, WARNING, ERROR, CRITICAL) %(levelname)s Text logging level for the message ("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL") %(pathname)s Full pathname of the source file where the logging call was issued (if available) %(filename)s Filename portion of pathname %(module)s Module (name portion of filename) %(lineno)d Source line number where the logging call was issued (if available) %(funcName)s Function name %(created)f Time when the LogRecord was created (time.time() return value) %(asctime)s Textual time when the LogRecord was created %(msecs)d Millisecond portion of the creation time %(relativeCreated)d Time in milliseconds when the LogRecord was created, relative to the time the logging module was loaded (typically at application startup time) %(thread)d Thread ID (if available) %(threadName)s Thread name (if available) %(process)d Process ID (if available) %(message)s The result of record.getMessage(), computed just as the record is emitted

CustomFormatter for the logger.

Expand source code
class CustomFormatter(logging.Formatter):

    def __init__(self, dateformat: str = None):
        """
        CustomFormatter for the logger.
        """
        super().__init__()
        self.dateformat = dateformat

    def format(self, record: LogRecord) -> str:
        """
        Formats the provided LogRecord instance.
        Returns:
            Formatted LogRecord as string.
        """
        # Set format and colors
        grey = "\033[38;20m"
        green = "\033[32;20m"
        yellow = "\033[33;20m"
        red = "\033[31;20m"
        bold_red = "\033[31;1m"
        reset = "\033[0m"
        format_ = '[%(levelname)-8s] - {datetime} - %(message)s'.format(
            datetime=datetime.now().astimezone().strftime('%Y-%m-%dT%H:%M:%S.%f%z')
        )

        self.FORMATS = {
            logging.DEBUG: green + format_ + reset,
            logging.INFO: grey + format_ + reset,
            logging.WARNING: yellow + format_ + reset,
            logging.ERROR: red + format_ + reset,
            logging.CRITICAL: bold_red + format_ + reset
        }

        log_format = self.FORMATS.get(record.levelno)

        formatter = logging.Formatter(log_format, datefmt=self.dateformat)
        return formatter.format(record)

Ancestors

  • logging.Formatter

Methods

def format(self, record: logging.LogRecord) ‑> str

Formats the provided LogRecord instance.

Returns

Formatted LogRecord as string.

Expand source code
def format(self, record: LogRecord) -> str:
    """
    Formats the provided LogRecord instance.
    Returns:
        Formatted LogRecord as string.
    """
    # Set format and colors
    grey = "\033[38;20m"
    green = "\033[32;20m"
    yellow = "\033[33;20m"
    red = "\033[31;20m"
    bold_red = "\033[31;1m"
    reset = "\033[0m"
    format_ = '[%(levelname)-8s] - {datetime} - %(message)s'.format(
        datetime=datetime.now().astimezone().strftime('%Y-%m-%dT%H:%M:%S.%f%z')
    )

    self.FORMATS = {
        logging.DEBUG: green + format_ + reset,
        logging.INFO: grey + format_ + reset,
        logging.WARNING: yellow + format_ + reset,
        logging.ERROR: red + format_ + reset,
        logging.CRITICAL: bold_red + format_ + reset
    }

    log_format = self.FORMATS.get(record.levelno)

    formatter = logging.Formatter(log_format, datefmt=self.dateformat)
    return formatter.format(record)
class Logger

Stores and processes the logs

Expand source code
class Logger:  # pylint: disable=too-many-instance-attributes
    """ Stores and processes the logs """

    @staticmethod
    def set_logger_setup() -> None:
        """
        Sets the logger setup with a predefined configuration.
        """

        log_config_dict = Logger.generate_logging_config_dict()
        dictConfig(log_config_dict)
        rotating_file_handler = RotatingFileHandler(filename='training_logs.log', mode='a', maxBytes=50000000,
                                                    backupCount=10, encoding='utf-8')
        rotating_file_handler.setFormatter(logging.Formatter(
            '"%(levelname)s"|"{datetime}"|%(message)s'.format(datetime=datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%fZ'))
        ))
        rotating_file_handler.setLevel(logging.INFO)
        logger = get_global_logger()
        logger.addHandler(rotating_file_handler)
        logger.setLevel(20)

    @staticmethod
    def generate_logging_config_dict() -> dict:
        """
        Generates the configuration dictionary that is used to configure the logger.
        Returns:
            Configuration dictionary.
        """
        return {
            'version': 1,
            'disable_existing_loggers': False,
            'formatters': {
                'custom_formatter': {
                    '()': CustomFormatter,
                    'dateformat': '%Y-%m-%dT%H:%M:%S.%06d%z'
                },
            },
            'handlers': {
                'debug_console_handler': {
                    'level': 'NOTSET',
                    'formatter': 'custom_formatter',
                    'class': 'logging.StreamHandler',
                    'stream': 'ext://sys.stdout',
                }
            },
            'loggers': {
                '': {
                    'handlers': ['debug_console_handler'],
                    'level': 'NOTSET',
                },
            }
        }

Static methods

def generate_logging_config_dict() ‑> dict

Generates the configuration dictionary that is used to configure the logger.

Returns

Configuration dictionary.

Expand source code
@staticmethod
def generate_logging_config_dict() -> dict:
    """
    Generates the configuration dictionary that is used to configure the logger.
    Returns:
        Configuration dictionary.
    """
    return {
        'version': 1,
        'disable_existing_loggers': False,
        'formatters': {
            'custom_formatter': {
                '()': CustomFormatter,
                'dateformat': '%Y-%m-%dT%H:%M:%S.%06d%z'
            },
        },
        'handlers': {
            'debug_console_handler': {
                'level': 'NOTSET',
                'formatter': 'custom_formatter',
                'class': 'logging.StreamHandler',
                'stream': 'ext://sys.stdout',
            }
        },
        'loggers': {
            '': {
                'handlers': ['debug_console_handler'],
                'level': 'NOTSET',
            },
        }
    }
def set_logger_setup() ‑> None

Sets the logger setup with a predefined configuration.

Expand source code
@staticmethod
def set_logger_setup() -> None:
    """
    Sets the logger setup with a predefined configuration.
    """

    log_config_dict = Logger.generate_logging_config_dict()
    dictConfig(log_config_dict)
    rotating_file_handler = RotatingFileHandler(filename='training_logs.log', mode='a', maxBytes=50000000,
                                                backupCount=10, encoding='utf-8')
    rotating_file_handler.setFormatter(logging.Formatter(
        '"%(levelname)s"|"{datetime}"|%(message)s'.format(datetime=datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%fZ'))
    ))
    rotating_file_handler.setLevel(logging.INFO)
    logger = get_global_logger()
    logger.addHandler(rotating_file_handler)
    logger.setLevel(20)