I am trying to do a log for my application. I want to add an attribute so I would know in what class is the log. I have starting a test to see if it works:
#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;
}
Now I am stuck...
- How it would be better to do?
- How to set the attribute to the wanted value?
- Shall I do the BoostLogger members static?
Thanks for any advice. I have seen the boost log attributes tutorial (link1, link2, link3), but I have not found something that would help...