【发布时间】:2014-09-03 14:11:05
【问题描述】:
我正在使用 Boost 1.54 Logging API 并尝试更改控制台日志输出的颜色。以下是我正在使用的最小测试代码的链接(感觉代码有点长,直接发布):
所以,第 96 行有效,这是一个 std::cout 到控制台的彩色:
std::cout << colorSet( h, DARKTEAL )<<" I am coloured!!" << colorSet( h, GRAY ) << std::endl;
但是当我尝试在 boost::log::expressions::stream 中做同样的事情时,在第 77 行,打印的文本中没有颜色。
logging::formatter fmtconsole = expr::stream << colorSet( h, BLUE )<< "DEBUG:" << expr::smessage << colorSet( h, GRAY ) << "\n";
下面是我得到的输出的屏幕截图:
我记得在 Boost sourceforge 论坛上读过 Andrey Semashev 的一篇文章,可以编写自定义格式化程序,将颜色控制代码添加到输出中,但 AFIK 仅适用于 Linux 终端,这就是我尝试的原因这种方法。
有没有办法做到这一点?
谢谢。
更新:
所以我实现它的方法是按照 Semasheve 的建议提供自定义格式化函数:
void my_formatter(logging::record_view const& rec, logging::formatting_ostream& strm)
{
HANDLE h = GetStdHandle( STD_OUTPUT_HANDLE );
// Finally, put the record message to the stream
boost::locale::generator gen;
std::locale::global(gen(""));
boost::locale::date_time now;
std::cout.imbue(std::locale());
std::cout << colorSet( h, BLUE ) << boost::locale::as::ftime( "%H:%M:%S" ) << "[" << now << "] ";
std::cout << colorSet( h, RED ) << rec[expr::smessage] << colorSet( h, GRAY );
}
请参阅主代码链接以查看 colorSet 定义。
然后为后端设置格式化程序,如:
consolebackend->set_formatter( &my_formatter );
不幸的是,我没有使用formatting_ostream 对象,这使得这不是一个很好的解决方案。而我不能使用它的原因是因为 Boost 刷新流的方式。所以我只会得到流中的最后一种颜色。因此我最终直接使用了 std::cout。
但我相信这是可能的,不知何故。
虽然这样可以完成工作,但我仍然需要一种机制,通过该机制我可以将流作为临时对象,可以从宏中调用。
可能是这样的:
class TMP_LOG
{
public:
TMP_LOG(const Color& c) : col(c), m_str() { }
~TMP_LOG()
{
HANDLE h = GetStdHandle( STD_OUTPUT_HANDLE );
SetConsoleTextAttribute(h, col);
BOOST_LOG_SEV( slg, normal ) << m_str.str();
SetConsoleTextAttribute(h, GRAY);
}
std::ostringstream& stream() { return m_str; }
private:
std::ostringstream m_str;
Color col;
};
#define LOG_DEBUG TMP_LOG(RED).stream()
#define LOG_WARN TMP_LOG(YELLOW).stream()
【问题讨论】: