How To Color Python Logging Output?

Better Stack Team
Updated on October 5, 2023

If you are new to logging in Python, please feel free to start with our Introduction to Python logging to get started smoothly. Otherwise, here is how to color python logging output:

đź”­ Want to centralize and monitor your python logs?

Go to Better Stack and start your log management in 5 minutes.

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:

 
handler.setFormatter(colorlog.ColoredFormatter('%(red)s%(levelname)s:%(name)s:%(message)s'))
logger.warning('colors')
Output
WARNING:__main__:colors

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github