Quickstart

If you haven’t installed Chromalog yet, it is highly recommended that you do so before reading any further.

How it works

Chromalog provides colored logging through the use of custom StreamHandler and Formatter.

The ColorizingStreamHandler is responsible for writing the log entries to the output stream. It can detect whether the associated stream has color capabilities and eventually fallback to a non-colored output mechanism. In this case it behaves exactly like a standard logging.StreamHandler. It is associated to a color map that is passed to every formatter that requests it.

The ColorizingFormatter is responsible for adding the color-specific markup in the formatted string. If used with a non colorizing stream handler, the ColorizingFormatter will transparently fallback to a non-colorizing behavior.

Fast setup

Chromalog provides a basicConfig function, very similar to logging.basicConfig() that quickly sets up the root logger, but using a ColorizingStreamHandler and a ColorizingFormatter instead.

It can be used like so to setup logging in a Python project:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import logging
import chromalog

chromalog.basicConfig(level=logging.DEBUG)
logger = logging.getLogger()

logger.debug("This is a debug message")
logger.info("This is an info message")
logger.warning("This is a warning message")
logger.error("This is an error message")
logger.critical("This is a critical message")

Which produces the following output:

_images/fast-setup.png

It’s as simple as it gets !

Marking log objects

While Chromalog has the ability to color entire log lines, it can also mark some specific log elements to highlight them in the output.

A good example of that could be:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import logging
import chromalog

from chromalog.mark.helpers.simple import success, error, important

chromalog.basicConfig(format="%(message)s", level=logging.INFO)
logger = logging.getLogger()

filename = r'/var/lib/status'

logger.info("Booting up system: %s", success("OK"))
logger.info("Booting up network: %s", error("FAIL"))
logger.info("Reading file at %s: %s", important(filename), success("OK"))

Which produces the following output:

_images/highlighting.png

Note what happens when we redirect the output to a file:

_images/highlighting-fallback.png

As you can see, Chromalog automatically detected that the output stream wasn’t color-capable and disabled automatically the colorizing. Awesome !

Checkout Marking functions for the complete list of available marking functions.

What’s next ?

Want to learn more about Chromalog ? Go read Advanced usage !