Reputation: 1185
I am using the boost trivial log with the default severity levels and I would like to map custom text for those default severity levels (e.g. instead of warning
use warn
).
In my formatter I use << boost::log::trivial::severity << " " << boost::log::expressions::smessage;
Logging a warning would be something like this:
BOOST_LOG_TRIVIAL(warning) << "Some log";
// What I would like to get logged
warn Some log
Here I saw an example of defining a custom severity_level (which did not work for me either) but in would prefer to keep using the default severity levels and just be able to define an operator<<
for it in order to change the severity level text.
I tried to define an custom operator<<
for the trivial severity_level
but I did not manage to make it work, not sure if that would even be possible.
Upvotes: 1
Views: 68
Reputation: 10614
In order to customize log record formatting you will have to configure a sink that will process log records. For the purpose of this answer I will assume you have created and added a sink that fits your use case.
You can use your own function for converting severity_level
values to strings by injecting it into the formatter expression. Given that the expression is implemented using Boost.Phoenix, you can use boost::phoenix::bind
for that:
std::string format_severity_level(
boost::log::value_ref<boost::log::trivial::severity_level,
boost::log::trivial::tag::severity> const& level)
{
std::string str;
// Check if the log record has a severity level attribute
if (level)
{
switch (*level)
{
case boost::log::trivial::severity_level::info:
str = "info";
break;
// ...
}
}
return str;
}
// Set the formatter in the sink
sink->set_formatter
(
boost::log::expressions::stream
<< "["
<< boost::phoenix::bind(
&format_severity_level, boost::log::trivial::severity.or_none())
<< "] " << boost::log::expressions::smessage
);
Here, boost::phoenix::bind
creates a function object that is injected into the formatter expression and gets called when the formatter is invoked. The boost::log::trivial::severity
placeholder is used to extract the severity level attribute value from the log record and pass it, wrapped in value_ref
, to your format_severity_level
function that would convert it to a string. The .or_none()
call indicates that in case if no such attribute is attached to the log record, the call should proceed with an empty value_ref
, which format_severity_level
is supposed to test for.
Upvotes: 1