I have a program that log things to STDOUT.
Those log entries have an associated “log level” (debug, warning, information, and so on) and I’d like to give the user the ability to color this output, depending on the log level.
What is the way of determining if STDOUT is attached to a terminal that is-color capable ?
And how can I output my text with colors then ?
I’m looking for a solution that involves only C or C++ calls. I guess curses (or ncurses) has something to ease this, but I’d like to avoid its use to keep my dependencies to a minimum.
Probably the easiest way to check is simply:
This will return
1if your standard output is being sent to any sort of terminal. In practice, any terminal will either support or ignore VT100 color codes; examining terminfo is unnecessary unless you expect to be outputting to certain really unusual hardware terminals. (Most of which haven’t been made in decades.)To output colors, use the (extended) SGR sequence:
where
%dis one of the following values for commonly supported colors:There are more values, but these are the most widely supported ones. Again, examining terminfo is largely unnecessary for these control codes, as every software terminal worth its salt will support (or ignore) them.
If you need to change multiple attributes at once, you can specify them all at once, separated by semicolons. For instance, the following sequence will sear your eyeballs with bold magenta text on a green background: