...
BOOST_LOG_TRIVIAL(info) << "my log message";
...
I don't have a proper file logger implement yet, I've been thinking to use log4cxx but then I give up since I begin it with Boost Log. From my experience on log4j, to implement a file logger in Boost Log, it would be a simple task to do provided I have followed the documentation. Otherwise, it's going to be so hard to do it. I found a working sample used for logging the file name and file number in the log in StackOverflow. This is what I need to do for my case, I define my logger in FileBot.h:...
#define LOGGER(logger, sev) \
BOOST_LOG_STREAM_WITH_PARAMS( \
(logger), \
(set_get_attrib("FILE", path_to_filename(__FILE__))) \
(set_get_attrib("LINE", __LINE__)) \
(::boost::log::keywords::severity = (boost::log::trivial::sev)) \
)
...
The the bunch of utility function mention in the above #define in CPP file.
...
template<typename valuetype="">
ValueType set_get_attrib(const char* name, ValueType value)
{
auto attr = logging::attribute_cast<logging::attributes::mutable_constant aluetype="">>(logging::core::get()->get_thread_attributes()[name]);
attr.set(value);
return attr.get();
}
std::string path_to_filename(std::string path)
{
return path.substr(path.find_last_of("/\\")+1);
}
...
And then the initialize code in FileBot constructor:
...
FileBot::FileBot()
{
logging::core::get()->add_thread_attribute("FILE", boost::log::attributes::mutable_constant<string>(""));
logging::core::get()->add_thread_attribute("LINE", boost::log::attributes::mutable_constant<int>(0));
logging::add_file_log
(
logging::keywords::file_name = "/home/kokhoe/workspaceqt/debug/sample_%N.log",
logging::keywords::rotation_size = 10 * 1024 * 1024,
logging::keywords::time_based_rotation = logging::sinks::file::rotation_at_time_point(0, 0, 0),
logging::keywords::format = (
expr::stream
<< expr::format_date_time< boost::posix_time::ptime >("TimeStamp", "%Y-%m-%d %H:%M:%S")
<< " [" << boost::log::trivial::severity << "] "
<< '[' << expr::attr<std::string>("FILE")
<< ':' << expr::attr<int>("LINE") << "] "
<< expr::smessage
)
);
logging::add_common_attributes();
...
The usage of the code is simply...
LOGGER(lg, info) << "my log message";
...
Then the output will show this:2019-02-19 22:03:26 [info] [FileBot.cpp:426] my log message
No comments:
Post a Comment