How To Color Python Logging Output?

Better Stack Team
Updated on May 4, 2022

Without External Module

Create a new custom formatter:

 
class CustomFormatter(logging.Formatter):

then create variables for the colors. They are created as ASCII code for an escape character followed by appropriate code sequence:

 
grey = "\\x1b[38;21m"
yellow = "\\x1b[33;21m"
red = "\\x1b[31;21m"
bold_red = "\\x1b[31;1m"
reset = "\\x1b[0m"
format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s (%(filename)s:%(lineno)d)"

You can discover all the possible colors here. Also specify the provided variable format.

After that, create a dictionary and specify a format for each of the log levels - color, your format of the log message, and reset the color at the end. Finally, make your formatter return this custom format:

 
FORMATS = {
        logging.DEBUG: grey + format + reset,
        logging.INFO: grey + format + reset,
        logging.WARNING: yellow + format + reset,
        logging.ERROR: red + format + reset,
        logging.CRITICAL: bold_red + format + reset
    }

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

And the whole formatter:

 
class CustomFormatter(logging.Formatter):
    grey = "\\x1b[38;21m"
    yellow = "\\x1b[33;21m"
    red = "\\x1b[31;21m"
    bold_red = "\\x1b[31;1m"
    reset = "\\x1b[0m"
    format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s (%(filename)s:%(lineno)d)"

    FORMATS = {
        logging.DEBUG: grey + format + reset,
        logging.INFO: grey + format + reset,
        logging.WARNING: yellow + format + reset,
        logging.ERROR: red + format + reset,
        logging.CRITICAL: bold_red + format + reset
    }

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

You can later assign this formatter to a handler:

 
handler.setFormatter(CustomFormatter())

Using External Module

For this, you can use an external module named colorlog. You can download it by running this command in the terminal:

 
pip install colorlog

You can read more about this module here.

After you installed the module, do not forget to import it:

 
import colorlog

Now using colorlog, create a handler using the class StreamHandler(). Then create a logger and assign this handler to it:

 
handler = colorlog.StreamHandler()

logger = colorlog.getLogger(__name__)
logger.addHandler(handler)

Now set a format for the handler. At the start, specify the desired color as an attribute and create some logging message: