consolidator

Форк
0
/
MyLogger.py 
129 строк · 5.1 Кб
1
import logging
2
import sys
3
from PySide6.QtCore import QObject,Signal
4

5

6
class EmittingStream(QObject):
7
    """ Класс для перехвата консольного вывода """
8
    textSignal = Signal(str)
9
    def write(self,text):
10
        self.textSignal.emit(f"{text}")
11
    def flush(self):
12
        """ Заглушка """
13
        pass
14

15
class MyQtLogHandler(logging.StreamHandler):
16
    """кастомный хэндлер для логирования
17

18
    Args:
19
        logging (_type_): _description_
20
    """
21
    on_same_line = False
22

23
    def emit(self, record):
24
        try:
25
            msg = self.format(record)
26
            stream:EmittingStream = self.stream
27
            same_line = hasattr(record, 'same_line')
28
            if self.on_same_line and not same_line:
29
                stream.write(self.terminator)
30
            stream.write(msg)
31
            if same_line:
32
                stream.write('... ')
33
                self.on_same_line = True
34
            else:
35
                stream.write(self.terminator)
36
                self.on_same_line = False
37
            self.flush()
38
        except (KeyboardInterrupt, SystemExit):
39
            raise
40
        except:
41
            self.handleError(record)
42

43
class CustomFormatter(logging.Formatter):
44

45
    header = "\x1b[96m"
46
    deb = "\x1b[94m"    
47
    grey = "\x1b[38;20m"
48
    green = "\x1b[92m"
49
    yellow = "\x1b[33;20m"
50
    red = "\x1b[31;20m"
51
    bold_red = "\x1b[31;1m"
52
    reset = "\x1b[0m"
53

54
    dt="<i style='color:silver'>%(asctime)s.%(msecs)03d</i>"
55
    debug_lev="<span style='color:AliceBlue'>%(levelname)s</span>"
56
    info_lev ="<span style='color:olive'>%(levelname)s</span>" 
57
    warn_lev ="<span style='color:SandyBrown'>%(levelname)s</span>" 
58
    error_lev ="<span style='color:crimson'>%(levelname)s</span>"
59
    critical_lev ="<b style='color:red'>%(levelname)s</b>"
60

61
    format = "%(asctime)s.%(msecs)03d - %(name)s - %(levelname)s - %(message)s (%(filename)s:%(lineno)d)"
62
    my_datefmt = "%d.%m.%Y %H:%M:%S"
63
    isConsole:bool = False
64

65
    format_type="simple" # simple, console, html 
66

67
    FORMATS_CONS = {
68
        logging.DEBUG: f"{header}%(asctime)s.%(msecs)03d{reset} - %(name)s - {deb}%(levelname)s{reset} - %(message)s",
69
        logging.INFO: f"{header}%(asctime)s.%(msecs)03d{reset} - %(name)s - {green}%(levelname)s{reset} - %(message)s",
70
        logging.WARNING: f"{header}%(asctime)s.%(msecs)03d{reset} - %(name)s - {yellow}%(levelname)s{reset} - %(message)s",
71
        logging.ERROR: f"{header}%(asctime)s.%(msecs)03d{reset} - %(name)s - {red}%(levelname)s{reset} - %(message)s",       
72
        logging.CRITICAL: f"{header}%(asctime)s.%(msecs)03d{reset} - %(name)s - {bold_red}%(levelname)s{reset} - %(message)s"
73
    }
74

75
    FORMATS_HTML = {
76
        logging.DEBUG: f"{dt} - %(name)s - {debug_lev} - %(message)s",
77
        logging.INFO: f"{dt} - %(name)s - {info_lev} - %(message)s",
78
        logging.WARNING: f"{dt} - %(name)s - {warn_lev} - %(message)s",
79
        logging.ERROR: f"{dt} - %(name)s - {error_lev} - %(message)s",       
80
        logging.CRITICAL: f"{dt} - %(name)s - {critical_lev} - %(message)s"
81
    }
82

83
    simple_file_format = "%(asctime)s.%(msecs)03d - %(name)s - %(levelname)s - %(message)s"
84
    file_format="%(asctime)s.%(msecs)03d - %(name)s - %(levelname)s - %(message)s (%(filename)s:%(lineno)d)"
85

86
    def format(self, record):
87
        log_fmt = self.simple_file_format
88
        if self.format_type=="console": log_fmt=self.FORMATS_CONS.get(record.levelno)
89
        elif 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_format
91
        if record.levelno>=logging.WARNING and self.format_type=="simple": log_fmt=self.file_format
92
        formatter = logging.Formatter(log_fmt,datefmt=self.my_datefmt)
93
        return formatter.format(record)
94
    
95
    def set_console(self):
96
        self.isConsole=True
97

98
    def set_format_type(self,ftype:str="simple"):
99
        self.format_type=ftype
100

101
class MyLogger(logging.Logger):
102
    
103
    def __init__(self, name: str, outStream:EmittingStream, level = logging.DEBUG , log_file:str="default.py",mode="a") -> None:        
104
        super().__init__(name,level)
105
        self.__init_handlers(log_file,mode,outStream)
106

107
    
108
    def logger_init(self,lg:logging.Logger):
109
        self=lg
110

111
    def __init_handlers(self,log_file:str,mode:str,stream:EmittingStream):
112
        fh = logging.FileHandler(log_file,mode=mode,encoding="utf-8")
113
        ch = logging.StreamHandler()
114
        qh = MyQtLogHandler()
115
        qh.setStream(stream)
116
        ch.setLevel(logging.DEBUG)
117
        fh.setLevel(logging.DEBUG)
118
        qh.setLevel(logging.DEBUG)
119
        fileFormatter = CustomFormatter()
120
        consoleFormatter:CustomFormatter = CustomFormatter()
121
        consoleFormatter.set_format_type("console")
122
        qtFormatter:CustomFormatter = CustomFormatter()
123
        qtFormatter.set_format_type("html")
124
        fh.setFormatter(fileFormatter)
125
        ch.setFormatter(consoleFormatter)
126
        qh.setFormatter(qtFormatter)
127
        self.addHandler(fh)
128
        self.addHandler(ch)
129
        if not isinstance(stream,type(sys.stdout)): self.addHandler(qh)
130
        
131

132

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.