Reputation: 3
I'm trying to set readable name to thread for the Boost logger instead of hex thread id. Here is how it looks now:
sink->set_formatter(
boost::log::expressions::stream << std::setw(5) <<
boost::log::expressions::attr <unsigned int>("LineID")
<< " [" << boost::log::expressions::format_date_time <boost::posix_time::ptime>("TimeStamp", "%H:%M:%S.%f")
<< "] <" << boost::log::expressions::attr <Severity_Level>("Severity")
<< "> (" << boost::log::expressions::attr <boost::log::attributes::current_thread_id::value_type> ("ThreadID")
<< ") " << boost::log::expressions::smessage);
My first thought was to make a map container or to use pthread_setname_np somehow. But the problem is how to insert this into boost logging structure. Is there any way to do this properly?
Upvotes: 0
Views: 1655
Reputation: 10614
You can add a thread-specific attribute with the thread name.
BOOST_LOG_ATTRIBUTE_KEYWORD(a_thread_name, "ThreadName", std::string)
void thread_entry()
{
boost::log::core::get()->add_thread_attribute("ThreadName",
boost::log::attributes::constant< std::string >("My thread name"));
// Your thread logic follows
}
This is typically done in your thread startup function.
You can use this attribute in filters and formatters the same way as any other attribute. For example:
sink->set_formatter(
boost::log::expressions::stream << std::setw(5) <<
boost::log::expressions::attr <unsigned int>("LineID")
<< " [" << boost::log::expressions::format_date_time <boost::posix_time::ptime>("TimeStamp", "%H:%M:%S.%f")
<< "] <" << boost::log::expressions::attr <Severity_Level>("Severity")
<< "> (" << boost::log::expressions::attr <boost::log::attributes::current_thread_id::value_type> ("ThreadID")
<< ", " << a_thread_name
<< ") " << boost::log::expressions::smessage);
You can learn more about thread-specific attributes, attribute keywords and constant
attribute from the docs.
Upvotes: 1