【发布时间】:2014-07-30 16:01:40
【问题描述】:
我正在尝试为我的应用程序记录日志。我想添加一个属性,这样我就知道日志在哪个类中。我已经开始测试它是否有效:
#include <boost/log/expressions.hpp>
#include <boost/log/attributes.hpp>
#include <boost/log/common.hpp>
#include <boost/log/sources/severity_logger.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
#include <boost/log/sinks/sync_frontend.hpp>
#include <boost/log/sinks/syslog_backend.hpp>
enum severity_levels
{
debug,
info,
warning,
error
};
typedef boost::log::sinks::synchronous_sink< boost::log::sinks::syslog_backend > SinkSysLogBackEnd;
typedef boost::log::sources::severity_logger< severity_levels > BoostLogger;
std::ostream& operator<< (std::ostream& strm, severity_levels level)
{
static const char* strings[] =
{
"debug",
"info",
"warning",
"error"
};
if (static_cast< std::size_t >(level) < sizeof(strings) / sizeof(*strings))
strm << strings[level];
else
strm << static_cast< int >(level);
return strm;
}
BOOST_LOG_ATTRIBUTE_KEYWORD(severity, "Severity", severity_levels)
BOOST_LOG_ATTRIBUTE_KEYWORD(executable, "Executable", std::string)
BOOST_LOG_ATTRIBUTE_KEYWORD(className, "Class name", std::string)
void init_syslog()
{
// Create a backend
boost::shared_ptr< SinkSysLogBackEnd > sink(new SinkSysLogBackEnd());
// We'll have to map our custom levels to the syslog levels
boost::log::sinks::syslog::custom_severity_mapping< severity_levels > mapping("Severity");
mapping[info] = boost::log::sinks::syslog::info;
mapping[warning] = boost::log::sinks::syslog::warning;
mapping[error] = boost::log::sinks::syslog::error;
sink->set_formatter(
boost::log::expressions::stream
// line id will be written in hex, 8-digits, zero-filled
<< executable << " <" << severity
<< "> : " << boost::log::expressions::smessage);
sink->locked_backend()->set_severity_mapper(mapping);
// Set the remote address to sent syslog messages to
sink->locked_backend()->set_target_address("localhost");
// Wrap it into the frontend and register in the core.
// The backend requires synchronization in the frontend.
boost::log::core::get()->add_sink(sink);
}
class Cls1
{
BoostLogger m_lg;
public:
Cls1()
{
// set the class name to Cls1
}
void foo()
{
// print log that has "Class Name" attribute set to "Cls1"
}
};
class Cls2
{
BoostLogger m_lg;
public:
Cls2()
{
// set the class name to Cls2
}
void foo()
{
// print log that has "Class Name" attribute set to "Cls2"
}
};
int main(int argc, char** argv)
{
init_syslog();
Cls1 o1;
o1.foo();
Cls2 o2;
o2.foo();
return 0;
}
现在我被卡住了......
- 怎么做会更好?
- 如何将属性设置为想要的值?
- 我应该将 BoostLogger 成员设为静态吗?
【问题讨论】: