1

I'm cusomizing logger module to add a few colors. Suppose I directed stream to a file as well. How can I read that file later? as in, which software shoud I use to read it properly as it seems to contain weird symbols (related of color formatting) that basic text editor doesn't know how to handle.

class CustomFormatter(logging.Formatter):
    """Logging colored formatter, adapted from https://stackoverflow.com/a/56944256/3638629"""

    grey = '\x1b[38;21m'
    blue = '\x1b[38;5;39m'
    yellow = '\x1b[38;5;226m'
    red = '\x1b[38;5;196m'
    bold_red = '\x1b[31;1m'
    reset = '\x1b[0m'

    def __init__(self, fmt):
        super().__init__()
        self.fmt = fmt
        self.FORMATS = {
            logging.DEBUG: self.grey + self.fmt + self.reset,
            logging.INFO: self.blue + self.fmt + self.reset,
            logging.WARNING: self.yellow + self.fmt + self.reset,
            logging.ERROR: self.red + self.fmt + self.reset,
            logging.CRITICAL: self.bold_red + self.fmt + self.reset
        }

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

Output:

enter image description here

Alex Deft
  • 2,531
  • 1
  • 19
  • 34

1 Answers1

0

I think you can write your logs to a binary file and then you can read them from the binary file.

You can make a python program that reads your binary file (after you written your logs in that file) and output the content to console.

PleSo
  • 314
  • 1
  • 11
  • Okay, thanks for the writing tip, although text works just as well in preserving it. Are you saying that python console is the only software that can recognize those writings? – Alex Deft Apr 14 '22 at 03:00
  • Okay, I'm doing this now. `print(loaded_text)` and it works. – Alex Deft Apr 14 '22 at 03:03
  • You are using special characters that are interpreted by the terminal in order to print them with different colours. So the short answer is no. The long one is that you can make your own software that can interpret these chars and print them coloured. Or you can think of writing to a file it in HTML format so, your text can be interpreted by browsers and you can use any kind of styling you want. You can make a function that can output to console in normal style and after that save the log in html format so you can view from browser. – PleSo Apr 14 '22 at 11:40