from datetime import datetime from pycolorize import colorize, cprint from enum import Enum import re # class MessageType(Enum): INFO = 10 SUCCESS = 20 WARNING = 30 ERROR = 40 CRITICAL = 50 # message_color = { 'INFO': 'gray', 'WARNING': 'yellow', 'ERROR': 'red', 'SUCCESS': 'cyan', 'CRITICAL': 'magenta' } class Logger: def __init__(self, fp, delimiter=' ', protected_mode=False): if protected_mode: self.__file = open(fp, 'x') else: self.__file = open(fp, 'w') self.__delimiter = delimiter # # self.__mcounter = { 'INFO': 0, 'WARNING': 0, 'ERROR': 0, 'SUCCESS': 0, 'CRITICAL': 0 }
def message(self, message, message_type: MessageType, to_print=True, include_microseconds=False): mt = str(message_type).replace('MessageType.', '') # INFO, WARNING, etc. # MessageType.TYPE # date = datetime.today().date() if not include_microseconds: time = datetime.today().time().replace(microsecond=0) else: time = datetime.today().time() # self.__mcounter[mt] += 1 # # join message = self.__delimiter.join([str(date), str(time), message, mt]) # , self.__file.write(re.sub(r'(\x1b\[.*?m)', '', message + '\n')) # re # print if to_print: cprint(message, message_color[mt])
def __check_head(self): template = self.__delimiter.join(['Date', 'Time', 'Message', 'Message type\n']) try: with open(self.__fp, 'r') as f: # , if f.readlines()[0] != template: self.__file.write(template) except IndexError: self.__file.write(template)
def __write_head(self): # template = self.__delimiter.join(['Date', 'Time', 'Message', 'Message type\n']) self.__file.write(template)
def get_stats(self): info = str(self.__['INFO']) warning = str(self.__mcounter['WARNING']) error = str(self.__mcounter['ERROR']) success = str(self.__mcounter['SUCCESS']) critical = str(self.__mcounter['CRITICAL']) # # cprint('INFO MESSAGES COUNT: {}\n' 'WARNING MESSAGES COUNT: {}\n' 'ERROR MESSAGES COUNT: {}\n' 'CRITICAL MESSAGES COUNT: {}\n' 'SUCCESS MESSAGES COUNT: {}'.format (colorize(info, 'magenta'), colorize(warning, 'magenta'), colorize(error, 'magenta'), colorize(critical, 'magenta'), colorize(success, 'magenta')), 'green')
class LogReader: def __init__(self, fp): self.__log = open(fp) def read_messages(self, message_type: MessageType=None): if message_type is None: # message type # # , color cprint() for line in self.__log.readlines()[1:]: line = line.strip() end = '' for char in line[::-1]: if not char.isspace(): end += char else: end = end[::-1] break try: cprint(line.strip(), message_color[end]) except KeyError: cprint('Key not found. Add it to message_color dict in sclogger module', 'yellow') # , # cprint(line.strip()) # else: end = str(message_type).replace('MessageType.', '') for line in self.__log.readlines(): line = line.strip() if line.endswith(end): cprint(line.strip(), message_color[end])
def close(self): # , self.__file.close()
Source: https://habr.com/ru/post/328266/
All Articles