I already knew about the color escapes, I used them in my bash prompt a while ago. Thanks anyway.
What I wanted was to integrate it with the logging module, which I eventually did after a couple of tries and errors.
Here is what I end up with:
BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
#The background is set with 40 plus the number of the color, and the foreground with 30
#These are the sequences need to get colored ouput
RESET_SEQ = "\033[0m"
COLOR_SEQ = "\033[1;%dm"
BOLD_SEQ = "\033[1m"
def formatter_message(message, use_color = True):
if use_color:
message = message.replace("$RESET", RESET_SEQ).replace("$BOLD", BOLD_SEQ)
else:
message = message.replace("$RESET", "").replace("$BOLD", "")
return message
COLORS = {
'WARNING': YELLOW,
'INFO': WHITE,
'DEBUG': BLUE,
'CRITICAL': YELLOW,
'ERROR': RED
}
class ColoredFormatter(logging.Formatter):
def __init__(self, msg, use_color = True):
logging.Formatter.__init__(self, msg)
self.use_color = use_color
def format(self, record):
levelname = record.levelname
if self.use_color and levelname in COLORS:
levelname_color = COLOR_SEQ % (30 + COLORS[levelname]) + levelname + RESET_SEQ
record.levelname = levelname_color
return logging.Formatter.format(self, record)
And to use it, create your own Logger:
# Custom logger class with multiple destinations
class ColoredLogger(logging.Logger):
FORMAT = "[$BOLD%(name)-20s$RESET][%(levelname)-18s] %(message)s ($BOLD%(filename)s$RESET:%(lineno)d)"
COLOR_FORMAT = formatter_message(FORMAT, True)
def __init__(self, name):
logging.Logger.__init__(self, name, logging.DEBUG)
color_formatter = ColoredFormatter(self.COLOR_FORMAT)
console = logging.StreamHandler()
console.setFormatter(color_formatter)
self.addHandler(console)
return
logging.setLoggerClass(ColoredLogger)
Just in case anyone else needs it.
Be 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. If you have configured file loggers etc. you probably don't want to have the colors in the log files. To avoid that, it's probably best to simply create a copy of record
with copy.copy()
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).
Below you can find colors reference of text to command when running node.js application:
console.log('\x1b[36m%s\x1b[0m', 'I am cyan'); //cyan
console.log('\x1b[33m%s\x1b[0m', stringToMakeYellow); //yellow
Note %s
is where in the string (the second argument) gets injected. \x1b[0m
resets the terminal color so it doesn't continue to be the chosen color anymore after this point.
Colors reference
Reset = "\x1b[0m"
Bright = "\x1b[1m"
Dim = "\x1b[2m"
Underscore = "\x1b[4m"
Blink = "\x1b[5m"
Reverse = "\x1b[7m"
Hidden = "\x1b[8m"
FgBlack = "\x1b[30m"
FgRed = "\x1b[31m"
FgGreen = "\x1b[32m"
FgYellow = "\x1b[33m"
FgBlue = "\x1b[34m"
FgMagenta = "\x1b[35m"
FgCyan = "\x1b[36m"
FgWhite = "\x1b[37m"
BgBlack = "\x1b[40m"
BgRed = "\x1b[41m"
BgGreen = "\x1b[42m"
BgYellow = "\x1b[43m"
BgBlue = "\x1b[44m"
BgMagenta = "\x1b[45m"
BgCyan = "\x1b[46m"
BgWhite = "\x1b[47m"
EDIT:
For example, \x1b[31m
is an escape sequence that will be intercepted by your terminal and instructs it to switch to the red color. In fact, \x1b
is the code for the non-printable control character escape
. Escape sequences dealing only with colors and styles are also known as ANSI escape code and are standardized, so therefore they (should) work on any platform.
Wikipedia has a nice comparison of how different terminals display colors
https://en.wikipedia.org/wiki/ANSI_escape_code#Colors
Best Answer
The ANSI escape sequences you're looking for are the Select Graphic Rendition subset. All of these have the form
where
XXX
is a series of semicolon-separated parameters.To say, make text red, bold, and underlined (we'll discuss many other options below) in C you might write:
In C++ you'd use
In Python3 you'd use
and in Bash you'd use
where the first part makes the text red (
31
), bold (1
), underlined (4
) and the last part clears all this (0
).As described in the table below, there are a large number of text properties you can set, such as boldness, font, underlining, &c. (Isn't it silly that StackOverflow doesn't allow you to put proper tables in answers?)
Font Effects
n-10
5;<n>
or2;<r>;<g>;<b>
, see below5;<n>
or2;<r>;<g>;<b>
, see below2-bit Colours
You've got this already!
4-bit Colours
The standards implementing terminal colours began with limited (4-bit) options. The table below lists the RGB values of the background and foreground colours used for these by a variety of terminal emulators:
Using the above, you can make red text on a green background (but why?) using:
11 Colours (An Interlude)
In their book "Basic Color Terms: Their Universality and Evolution", Brent Berlin and Paul Kay used data collected from twenty different languages from a range of language families to identify eleven possible basic color categories: white, black, red, green, yellow, blue, brown, purple, pink, orange, and gray.
Berlin and Kay found that, in languages with fewer than the maximum eleven color categories, the colors followed a specific evolutionary pattern. This pattern is as follows:
This may be why story Beowulf only contains the colours black, white, and red. It may also be why the Bible does not contain the colour blue. Homer's Odyssey contains black almost 200 times and white about 100 times. Red appears 15 times, while yellow and green appear only 10 times. (More information here)
Differences between languages are also interesting: note the profusion of distinct colour words used by English vs. Chinese. However, digging deeper into these languages shows that each uses colour in distinct ways. (More information)
Generally speaking, the naming, use, and grouping of colours in human languages is fascinating. Now, back to the show.
8-bit (256) colours
Technology advanced, and tables of 256 pre-selected colours became available, as shown below.
Using these above, you can make pink text like so:
And make an early-morning blue background using
And, of course, you can combine these:
The 8-bit colours are arranged like so:
ALL THE COLOURS
Now we are living in the future, and the full RGB spectrum is available using:
So you can put pinkish text on a brownish background using
Support for "true color" terminals is listed here.
Much of the above is drawn from the Wikipedia page "ANSI escape code".
A Handy Script to Remind Yourself
Since I'm often in the position of trying to remember what colours are what, I have a handy script called:
~/bin/ansi_colours
:This prints