Skip to content

Coloredlogs

Colored terminal output for Python's logging module.

Example

import coloredlogs, logging

# Create a logger object.
logger = logging.getLogger(__name__)

# By default the install() function installs a handler on the root logger,
# this means that log messages from your code and log messages from the
# libraries that you use will all show up on the terminal.
coloredlogs.install(level='DEBUG')

# If you don't want to see log messages from libraries, you can pass a
# specific logger object to the install() function. In this case only log
# messages originating from that logger will show up on the terminal.
coloredlogs.install(level='DEBUG', logger=logger)

# Some examples.
logger.debug("this is a debugging message")
logger.info("this is an informational message")
logger.warning("this is a warning message")
logger.error("this is an error message")
logger.critical("this is a critical message")

File config example

Using coloredlogs.ColoredFormatter with logging.config.fileConfig

coloredformatter.py:

# -*- coding: utf-8 -*-

import coloredlogs


class ColoredFormatter(coloredlogs.ColoredFormatter):
    def __init__(self, fmt=None, datefmt=None, style='%'):
        '''Match coloredlogs.ColoredFormatter arguments with logging.Formatter'''
        coloredlogs.ColoredFormatter.__init__(self, fmt=fmt, datefmt=datefmt)

logging.conf:

[loggers]
keys=root

[logger_root]
level=DEBUG
handlers=console,logfile

[handlers]
keys=console,logfile

[handler_console]
class=StreamHandler
formatter=verbose_colored
args=(sys.stdout, )
level=DEBUG

[handler_logfile]
class=FileHandler
formatter=verbose
args=('log','a')
level=DEBUG

[formatters]
keys=verbose,verbose_colored,concise,concise_colored

[formatter_verbose]
class=logging.Formatter
format=[%(asctime)s.%(msecs)03d] [%(process)d/%(thread)s] [%(name)s.%(levelname)s] %(message)s
datefmt=%d/%b/%Y:%H:%M:%S

[formatter_verbose_colored]
class=coloredformatter.ColoredFormatter
format=[%(asctime)s.%(msecs)03d] [%(process)d/%(thread)s] [%(name)s.%(levelname)s] %(message)s
datefmt=%d/%b/%Y:%H:%M:%S

[formatter_concise]
class=logging.Formatter
format=[%(asctime)s] [%(name)s:%(levelname)s] %(message)s

[formatter_concise_colored]
class=coloredformatter.ColoredFormatter
format=[%(asctime)s] [%(name)s:%(levelname)s] %(message)s

main.py:

# -*- coding: utf-8 -*-

import logging

logging.config.fileConfig('logging.conf')
logging.debug('I will be colored')

See also

Favorite site