Blog Datasheets Home About me Clients My work Services Contact

G2Labs Grzegorz Grzęda

VT100 shell coloring for python logging

April 24, 2023

You can use my Python package vt100logging.

Install it: pip install vt100logging.

Or use this code snippet:

 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
import logging

LOGGER:logging.Logger

class VT100Formatter(logging.Formatter):

    green = "\x1b[32;20m"
    yellow = "\x1b[33;20m"
    red = "\x1b[31;20m"
    reset = "\x1b[0m"
    format = "%(asctime)s [%(name)s][%(levelname)s] %(message)s"

    FORMATS = {
        logging.INFO: green + format + reset,
        logging.WARNING: yellow + format + reset,
        logging.ERROR: red + format + reset,
    }

    def format(self, record):
        log_fmt = self.FORMATS.get(record.levelno)
        formatter = logging.Formatter(log_fmt)
        return formatter.format(record)


def initialize_logging(name):
    global LOGGER
    LOGGER = logging.getLogger(name)
    LOGGER.setLevel(logging.INFO)
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)
    ch.setFormatter(VT100Formatter())
    LOGGER.addHandler(ch)


def I(text):
    LOGGER.info(text)


def W(text):
    LOGGER.warning(text)


def E(text):
    LOGGER.error(text)


➡️ Git versioning projects


⬅️ Writing clean and SOLID code in object-oriented programming


Go back to Posts.