## ecr.log

src/ecr/log/__init__.py
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    import logging
    from typing import List, Dict
    from prompt_toolkit import HTML

    LOG_FORMAT = "#%(levelname)s|%(asctime)s|%(message)s"
    DATE_FORMAT = "%m/%d/%Y %H:%M:%S %p"

    class LogListHandler(logging.Handler):
        def __init__(self, data: List[str]):
            super().__init__()
            self.data = data

        def flush(self):
            self.acquire()
            try:
                pass
            finally:
                self.release()

        def emit(self, record):
            try:
                msg = self.format(record)
                self.data.append(msg)
                self.flush()
            except Exception:
                self.handleError(record)

    def initializeLogger(data: List[str], level=logging.INFO)->None:
        logging.basicConfig(level=level,
                            handlers=[LogListHandler(data)], format=LOG_FORMAT)

    levelToStyle: Dict[str, str] = {
        "DEBUG": 'fg="ansigreen"',
        "INFO": 'fg="ansicyan"',
        "WARNING": 'fg="ansiyellow"',
        "ERROR": 'fg="ansired"',
        "CRITICAL": 'fg="ansired"',
    }

    def colored(msg: str) -> HTML:
        if not msg.startswith("#"):
            return HTML(HTML(f'<obj>{msg}</obj>'))
        spl = msg[1:].split('|')
        bg, tme, data = spl[0], spl[1], "|".join(spl[2:])
        output = f'<obj {levelToStyle[bg]}>{bg}</obj> <obj fg="ansiblue">{tme}</obj> <obj>{data}</obj> '
        return HTML(output)

    info = logging.info
    debug = logging.debug
    warning = logging.warning
    error = logging.error
    critical = logging.critical

    def errorWithException(msg, *args):
        error(msg, *args, exc_info=True)