Reputation: 761
We've refactored our logger to use boost instead of our in-house logger which is not thread-safe. The problem is that all of our log calls around the project (thousands of lines of code) are ending with std::endl
. Now, our logger is thread safe but there is an extra empty line between records on the output.
This is how I initialize the logger:
void init()
{
boost::log::add_console_log
(
std::clog,
boost::log::keywords::format =
(
boost::log::expressions::stream << boost::log::expressions::format_date_time< boost::posix_time::ptime >("TimeStamp", "%Y-%m-%d %H:%M:%S")
<< " [" << boost::log::expressions::attr< LogLevel_e >("Severity") << "]: "
<< boost::log::expressions::smessage
)
);
}
It's a severity_logger_mt() object that is used to log our messages. I've read in their documentation that I might be able to prevent that empty line from happening if I create my own backend and frontend. It seems like too much of a hassle to create two modules just to prevent one extra empty line in the code.
Am I missing anything? is there an easier way to do it? Should I add more information to this question? Also, we're talking about boost 1.69.
Upvotes: 1
Views: 1090
Reputation: 10644
The newline is added automatically by the sink backend. The "right" way to fix it is to change your logging statements so that they don't end the message string with a newline. I consider it the right way because whether the trailing newline makes sense or not depends on the sink backend. The same log record can be processed by multiple sinks, and the newline may not be appropriate for all of them.
However, as a faster workaround, you may write your own formatter that will skip the trailing newline from the formatted string. There are a number of answers showing how to write a formatter (for example, here). Here's one way to do this:
std::string_view format_message(
boost::log::value_ref< std::string, boost::log::expressions::tag::smessage > const& message)
{
// Check to see if the attribute value has been found
if (message)
{
std::string_view msg = message.get();
if (!msg.empty() && msg.back() == '\n')
msg = std::string_view(msg.data(), msg.size() - 1);
return msg;
}
return std::string_view();
}
void init()
{
boost::log::add_console_log
(
std::clog,
boost::log::keywords::format =
(
boost::log::expressions::stream
<< boost::log::expressions::format_date_time< boost::posix_time::ptime >("TimeStamp", "%Y-%m-%d %H:%M:%S")
<< " [" << boost::log::expressions::attr< LogLevel_e >("Severity") << "]: "
<< boost::phoenix::bind(&format_message, boost::log::expressions::smessage.or_none())
)
);
}
Upvotes: 3