I am trying to make my team go away from log4cxx
and try to use Boost.Log v2
instead. Our current log4cxx pattern is rather simple:
log4cxx::helpers::Properties prop;
prop.setProperty("log4j.rootLogger","DEBUG, A1");
prop.setProperty("log4j.appender.A1","org.apache.log4j.ConsoleAppender");
prop.setProperty("log4j.appender.A1.layout","org.apache.log4j.PatternLayout");
prop.setProperty("log4j.appender.A1.layout.ConversionPattern","%d{ABSOLUTE} %-5p [%c] %m%n");
log4cxx::PropertyConfigurator::configure(prop);
However I failed to find a solution to support filename and line number printing. I've found so far an old post, but there is no clear solution (no accepted solution). I've looked into using those BOOST_LOG_NAMED_SCOPE
but they feel very ugly as it make it impossible to print the proper line number when multiple of those are used within the same function.
I've also found a simpler direct solution, here. But that also feel ugly, since it will print the fullpath, instead of just the basename (it is not configurable). So the fullpath and line number are always printed on a fixed location (before expr::smessage
).
I've found also this post, which looks like an old solution.
And finally the most promising solution, I found was here. However it does not even compile for me.
So my question is simply: how can I use Boost.Log v2 to print filename (not fullpath) and line number with minimal formatter flexibility (no solution with MACRO
and __FILE__
/ __LINE__
accepted, please). I'd appreciate a solution which does not involve BOOST_LOG_NAMED_SCOPE
, as described here:
If instead you want to see line numbers of particular log records then the best way is to define a custom macro which you will use to write logs. In that macro, you can add the file name and line number as attributes to the record (you can use manipulators for that). Note that in this case you won't be able to use these attributes in filters, but you probably don't need that.
In order to output filename and line you will need to register
Scopes
:and add custom formatter:
Note: In order for this to work the scopes container needs to be cleared before each logging:
if(!attributes::named_scope::get_scopes().empty()) attributes::named_scope::pop_scope();
I finally found a simple solution based on add_value. Here is the full source code:
On my Linux box, I compiled it using:
If you run and check the log file generated here is what you get:
My solution is based on two inputs (thanks!):