我最近用一个简单的自定义接收器后端做到了这一点
coloured_console_sink.h
#pragma once
#include <boost/log/sinks/basic_sink_backend.hpp>
class coloured_console_sink : public boost::log::sinks::basic_formatted_sink_backend<char, boost::log::sinks::synchronized_feeding>
{
public:
static void consume(boost::log::record_view const& rec, string_type const& formatted_string);
};
coloured_console_sink.cpp
#include "coloured_console_sink.h"
#include <iostream>
#include <windows.h>
#include <boost/log/trivial.hpp>
#include <boost/log/attributes/value_extraction.hpp>
#include <boost/log/attributes/attribute_value.hpp>
WORD get_colour(boost::log::trivial::severity_level level)
{
switch (level)
{
case boost::log::trivial::trace: return 0x08;
case boost::log::trivial::debug: return 0x07;
case boost::log::trivial::info: return 0x0F;
case boost::log::trivial::warning: return 0x0D;
case boost::log::trivial::error: return 0x0E;
case boost::log::trivial::fatal: return 0x0C;
default: return 0x0F;
}
}
void coloured_console_sink::consume(boost::log::record_view const& rec, string_type const& formatted_string)
{
auto level = rec.attribute_values()["Severity"].extract<boost::log::trivial::severity_level>();
auto hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(hstdout, &csbi);
SetConsoleTextAttribute(hstdout, get_colour(level.get()));
std::cout << formatted_string << std::endl;
SetConsoleTextAttribute(hstdout, csbi.wAttributes);
}
用法
typedef boost::log::sinks::synchronous_sink<coloured_console_sink> coloured_console_sink_t;
auto coloured_console_sink = boost::make_shared<coloured_console_sink_t>();
boost::log::core::get()->add_sink(coloured_console_sink);