

Then I came across this page and found a collection of code snippets that people are copy/pasting :-(. Years ago I wrote a colored stream handler for my own use.

#420 EMOJI COPY AND PASTE TEXT HOW TO#
Here are instructions on how to enable them, which I haven't try Looks like the Windows command prompt doesn't have colors at all by default. This solution works on Mac OS, IDE terminals. # create console handler with a higher log level Instantiate logger # create logger with 'spam_application' Logging.CRITICAL: bold_red + format + reset Logging.WARNING: yellow + format + reset, To avoid that, it's probably best to simply create a copy of record with py() before manipulating the levelname attribute, or to reset the levelname to the previous value, before returning the formatted string (credit to Michael in the comments).Ģ022 solution, no additional packages required, Python 3Ĭlass CustomFormatter(logging.Formatter):įormat = "%(asctime)s - %(name)s - %(levelname)s - %(message)s (%(filename)s:%(lineno)d)" you probably don't want to have the colors in the log files. Logging.Logger._init_(self, name, logging.DEBUG)Ĭolor_formatter = ColoredFormatter(self.COLOR_FORMAT)īe careful if you're using more than one logger or handler: ColoredFormatter is changing the record object, which is passed further to other handlers or propagated to other loggers. Return (self, record)Īnd to use it, create your own Logger: # Custom logger class with multiple destinationsįORMAT = " %(message)s ($BOLD%(filename)s$RESET:%(lineno)d)"ĬOLOR_FORMAT = formatter_message(FORMAT, True) Levelname_color = COLOR_SEQ % (30 + COLORS) + levelname + RESET_SEQ Message = message.replace("$RESET", "").replace("$BOLD", "")Ĭlass ColoredFormatter(logging.Formatter):ĭef _init_(self, msg, use_color = True): Message = message.replace("$RESET", RESET_SEQ).replace("$BOLD", BOLD_SEQ) #These are the sequences need to get colored ouputĭef formatter_message(message, use_color = True): #The background is set with 40 plus the number of the color, and the foreground with 30 Here is what I end up with: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8) What I wanted was to integrate it with the logging module, which I eventually did after a couple of tries and errors. I already knew about the color escapes, I used them in my bash prompt a while ago.
