标签:
#include <string>
#include <fstream>
#include <iomanip>
#include <boost/log/core.hpp>
#include <boost/smart_ptr.hpp>
#include <boost/log/sinks.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/utility/setup.hpp>
#include <boost/log/sources/record_ostream.hpp>
#include <boost/log/sources/severity_logger.hpp>
#include <boost/log/attributes/scoped_attribute.hpp>
enum severity_level
{
normal,
notification,
warning,
error,
critical
};
BOOST_LOG_ATTRIBUTE_KEYWORD(tag_attr, "Tag", std::string)
BOOST_LOG_ATTRIBUTE_KEYWORD(line_id, "LineID", unsigned int)
BOOST_LOG_ATTRIBUTE_KEYWORD(severity, "Severity", severity_level)
void init()
{
boost::log::formatter fmt = boost::log::expressions::stream
<< std::setw(6) << std::setfill(‘0‘) << line_id << std::setfill(‘ ‘)
<< ": <" << severity << ">\t"
<< boost::log::expressions::if_(boost::log::expressions::has_attr(tag_attr))
[
boost::log::expressions::stream << "[" << tag_attr << "] "
]
<< boost::log::expressions::smessage;
// Initialize sinks
typedef boost::log::sinks::synchronous_sink< boost::log::sinks::text_ostream_backend > text_sink;
boost::shared_ptr< text_sink > sink = boost::make_shared< text_sink >();
sink->locked_backend()->add_stream(boost::make_shared< std::ofstream >("full.log"));
sink->set_formatter(fmt);
boost::log::core::get()->add_sink(sink);
sink = boost::make_shared< text_sink >();
sink->locked_backend()->add_stream(boost::make_shared< std::ofstream >("important.log"));
sink->set_formatter(fmt);
sink->set_filter(severity >= warning || (boost::log::expressions::has_attr(tag_attr) && tag_attr == "IMPORTANT_MESSAGE"));
boost::log::core::get()->add_sink(sink);
// Add attributes
boost::log::add_common_attributes();
}
void logging_function()
{
boost::log::sources::severity_logger< severity_level > slg;
BOOST_LOG_SEV(slg, normal) << "A regular message";
BOOST_LOG_SEV(slg, warning) << "Something bad is going on but I can handle it";
BOOST_LOG_SEV(slg, critical) << "Everything crumbles, shoot me now!";
{
BOOST_LOG_SCOPED_THREAD_TAG("Tag", "IMPORTANT_MESSAGE");
BOOST_LOG_SEV(slg, normal) << "An important message";
}
}
int main(int, char*[])
{
init();
logging_function();
return 0;
}
bool my_filter(boost::log::value_ref< severity_level, tag::severity > const& level,
boost::log::value_ref< std::string, tag::tag_attr > const& tag)
{
return level >= warning || tag == "IMPORTANT_MESSAGE";
}
void init()
{
// ...
sink->set_filter(boost::phoenix::bind(&my_filter, severity.or_none(), tag_attr.or_none()));
// ...
}
标签:
原文地址:http://www.cnblogs.com/zhangpanyi/p/4484306.html