bobeff bobeff - 26 days ago 18
C++ Question

How to add color coding to boost::log console output?

I'm trying to add colored log output for boost::log under linux. I read the following and I tried this:

#define MY_LOG_ERROR() BOOST_LOG_TRIVIAL(error) << "\033[1;31"

MY_LOG_ERROR() << "This is an error log."


but it gives me the result below:


[2016-07-11 17:23:16.328435] [0x00007f15f03d6780] [error] [1;31This
is an error log.


How to properly add colored log output to boost::log?

Answer

The proper way to customize output with Boost.Log is to use formatters. To set a formatter you will have to set up a sink for that as described here, but you can keep using the BOOST_LOG_TRIVIAL macro for generating log records.

The good thing about formatters is that you can have access to log record attributes like severity level within the formatter. For example, you could use the severity level to choose the color of the formatted log record on the console.

void coloring_formatter(
    logging::record_view const& rec, logging::formatting_ostream& strm)
{
    auto severity = rec[logging::trivial::severity];
    if (severity)
    {
        // Set the color
        switch (severity.get())
        {
        case logging::trivial::severity::info:
            strm << "\033[32m";
            break;
        case logging::trivial::severity::warning:
            strm << "\033[33m";
            break;
        case logging::trivial::severity::error:
        case logging::trivial::severity::fatal:
            strm << "\033[31m";
            break;
        default:
            break;
        }
    }

    // Format the message here...
    strm << rec[logging::expressions::smessage];

    if (severity)
    {
        // Restore the default color
        strm << "\033[0m";
    }
}

sink->set_formatter(&coloring_formatter);
Comments