本文介绍了如何添加颜色编码以增强boost :: log控制台输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Linux下为boost :: log添加彩色日志输出.我阅读了以下内容,并且我尝试了:

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:

如何正确地将彩色日志输出添加到boost :: log?

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

推荐答案

使用Boost.Log自定义输出的正确方法是使用格式化程序.要设置格式化程序,您将必须为此设置接收器,如此处,但是您可以继续使用BOOST_LOG_TRIVIAL宏来生成日志记录.

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);

这篇关于如何添加颜色编码以增强boost :: log控制台输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 05:29