consolidator
/
MyLogger.py
129 строк · 5.1 Кб
1import logging2import sys3from PySide6.QtCore import QObject,Signal4
5
6class EmittingStream(QObject):7""" Класс для перехвата консольного вывода """8textSignal = Signal(str)9def write(self,text):10self.textSignal.emit(f"{text}")11def flush(self):12""" Заглушка """13pass14
15class MyQtLogHandler(logging.StreamHandler):16"""кастомный хэндлер для логирования17
18Args:
19logging (_type_): _description_
20"""
21on_same_line = False22
23def emit(self, record):24try:25msg = self.format(record)26stream:EmittingStream = self.stream27same_line = hasattr(record, 'same_line')28if self.on_same_line and not same_line:29stream.write(self.terminator)30stream.write(msg)31if same_line:32stream.write('... ')33self.on_same_line = True34else:35stream.write(self.terminator)36self.on_same_line = False37self.flush()38except (KeyboardInterrupt, SystemExit):39raise40except:41self.handleError(record)42
43class CustomFormatter(logging.Formatter):44
45header = "\x1b[96m"46deb = "\x1b[94m"47grey = "\x1b[38;20m"48green = "\x1b[92m"49yellow = "\x1b[33;20m"50red = "\x1b[31;20m"51bold_red = "\x1b[31;1m"52reset = "\x1b[0m"53
54dt="<i style='color:silver'>%(asctime)s.%(msecs)03d</i>"55debug_lev="<span style='color:AliceBlue'>%(levelname)s</span>"56info_lev ="<span style='color:olive'>%(levelname)s</span>"57warn_lev ="<span style='color:SandyBrown'>%(levelname)s</span>"58error_lev ="<span style='color:crimson'>%(levelname)s</span>"59critical_lev ="<b style='color:red'>%(levelname)s</b>"60
61format = "%(asctime)s.%(msecs)03d - %(name)s - %(levelname)s - %(message)s (%(filename)s:%(lineno)d)"62my_datefmt = "%d.%m.%Y %H:%M:%S"63isConsole:bool = False64
65format_type="simple" # simple, console, html66
67FORMATS_CONS = {68logging.DEBUG: f"{header}%(asctime)s.%(msecs)03d{reset} - %(name)s - {deb}%(levelname)s{reset} - %(message)s",69logging.INFO: f"{header}%(asctime)s.%(msecs)03d{reset} - %(name)s - {green}%(levelname)s{reset} - %(message)s",70logging.WARNING: f"{header}%(asctime)s.%(msecs)03d{reset} - %(name)s - {yellow}%(levelname)s{reset} - %(message)s",71logging.ERROR: f"{header}%(asctime)s.%(msecs)03d{reset} - %(name)s - {red}%(levelname)s{reset} - %(message)s",72logging.CRITICAL: f"{header}%(asctime)s.%(msecs)03d{reset} - %(name)s - {bold_red}%(levelname)s{reset} - %(message)s"73}74
75FORMATS_HTML = {76logging.DEBUG: f"{dt} - %(name)s - {debug_lev} - %(message)s",77logging.INFO: f"{dt} - %(name)s - {info_lev} - %(message)s",78logging.WARNING: f"{dt} - %(name)s - {warn_lev} - %(message)s",79logging.ERROR: f"{dt} - %(name)s - {error_lev} - %(message)s",80logging.CRITICAL: f"{dt} - %(name)s - {critical_lev} - %(message)s"81}82
83simple_file_format = "%(asctime)s.%(msecs)03d - %(name)s - %(levelname)s - %(message)s"84file_format="%(asctime)s.%(msecs)03d - %(name)s - %(levelname)s - %(message)s (%(filename)s:%(lineno)d)"85
86def format(self, record):87log_fmt = self.simple_file_format88if self.format_type=="console": log_fmt=self.FORMATS_CONS.get(record.levelno)89elif self.format_type=="html": log_fmt=self.FORMATS_HTML.get(record.levelno)90# log_fmt = self.FORMATS_CONS.get(record.levelno) if self.isConsole else self.simple_file_format91if record.levelno>=logging.WARNING and self.format_type=="simple": log_fmt=self.file_format92formatter = logging.Formatter(log_fmt,datefmt=self.my_datefmt)93return formatter.format(record)94
95def set_console(self):96self.isConsole=True97
98def set_format_type(self,ftype:str="simple"):99self.format_type=ftype100
101class MyLogger(logging.Logger):102
103def __init__(self, name: str, outStream:EmittingStream, level = logging.DEBUG , log_file:str="default.py",mode="a") -> None:104super().__init__(name,level)105self.__init_handlers(log_file,mode,outStream)106
107
108def logger_init(self,lg:logging.Logger):109self=lg110
111def __init_handlers(self,log_file:str,mode:str,stream:EmittingStream):112fh = logging.FileHandler(log_file,mode=mode,encoding="utf-8")113ch = logging.StreamHandler()114qh = MyQtLogHandler()115qh.setStream(stream)116ch.setLevel(logging.DEBUG)117fh.setLevel(logging.DEBUG)118qh.setLevel(logging.DEBUG)119fileFormatter = CustomFormatter()120consoleFormatter:CustomFormatter = CustomFormatter()121consoleFormatter.set_format_type("console")122qtFormatter:CustomFormatter = CustomFormatter()123qtFormatter.set_format_type("html")124fh.setFormatter(fileFormatter)125ch.setFormatter(consoleFormatter)126qh.setFormatter(qtFormatter)127self.addHandler(fh)128self.addHandler(ch)129if not isinstance(stream,type(sys.stdout)): self.addHandler(qh)130
131
132