123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130 |
- # -*- coding: utf-8 -*-
- """
- @author: jürgen.pannosch, tanja.zolotareva
- """
- import sys
- import os
- import logging
- from datetime import datetime
- sys.path.append(os.getcwd())
- class Log():
- '''
- '''
- pass
- def __init__(self, name: str = None,
- log_file: str = None,
- log_level: str = "ERROR",
- stdout_log_level: str = "INFO",
- print_to_stdout: bool = True):
- """Sets the log level and the path where the log file is stored
- :param log_file: Path to the log file.
- :param log_level: Log level."""
- if name is None:
- name = ''
- self._logger = logging.getLogger(name)
-
- self._logger.setLevel("DEBUG")
- if (self._logger.hasHandlers()):
- self._logger.handlers.clear()
- if log_file is None:
- log_file = os.path.join(".", "logs", str(datetime.today().date()) + ".log")
- assert(isinstance(log_file, str)),\
- "Parameter 'log_path' must be of string type"
- os.makedirs(os.path.dirname(log_file), exist_ok=True)
- formatter = logging.Formatter(
- '\n %(name)s %(asctime)s %(levelname)s %(message)s')
- file_handler = logging.FileHandler(log_file)
- file_handler.setFormatter(formatter)
- file_handler.setLevel(log_level)
- self._logger.addHandler(file_handler)
- if print_to_stdout:
- stream_handler = logging.StreamHandler(sys.stdout)
- stream_handler.setFormatter(formatter)
- stream_handler.setLevel(stdout_log_level)
- self._logger.addHandler(stream_handler)
- # self._logger.setLevel(log_level)
- @property
- def magenta(self):
- return '\033[95m'
- @property
- def blue(self):
- return '\033[94m'
- @property
- def cyan(self):
- return '\u001b[36m'
- @property
- def green(self):
- return '\033[92m'
- @property
- def yellow(self):
- return '\033[93m'
- @property
- def fail(self):
- return '\033[91m'
- @property
- def reset(self):
- return '\033[0m'
- @property
- def bold(self):
- return '\033[1m'
- @property
- def underline(self):
- return '\033[4m'
- def info(self, message: str):
- self._logger.info(message)
- def warning(self, message: str):
- self._logger.warning(message)
- def error(self, message: str):
- self._logger.error(message)
- def log_and_raise_error(self, message):
- '''
- '''
- self._logger.error(message, exc_info=True)
- raise Exception(message)
- def log_and_raise_error_stack_info(self, message):
- '''
- '''
- self._logger.error(message, exc_info=True, stack_info=True)
- raise Exception(message)
- def log_and_raise_warning(self, message):
- '''
- '''
- self._logger.warning(message)
- raise Warning(message)
|