Reputation: 2861
I have the following (simplified) code in my C++ program:
std::string DataRequest::toString() const {
LOG4CPLUS_TRACE(logger,
LOG4CPLUS_TEXT("symbol=" << m_contract.symbol));
std::ostringstream oss;
oss << "id=" << reqId
<< ",symbol=" << m_contract.symbol;
return oss.str();
}
and
int DataService::requestData(
DataRequest request) {
LOG4CPLUS_INFO(logger, LOG4CPLUS_TEXT("requestData: " << request.toString()));
}
This code then produces the log message:
TRACE symbol=AAA
INFO symbol=AAArequestData: id=1,symbol=AAA
however I was expecting
TRACE symbol=AAA
INFO requestData: id=1,symbol=AAA
Since there is a log4cplus message being generated within a log4cplus message it appears to be concatenating the two messages into a single message. Is this normal behaviour? Is there a solution to force each message to be generated independently?
Upvotes: 2
Views: 546
Reputation: 18238
This is wrong code
LOG4CPLUS_TRACE(logger,
LOG4CPLUS_TEXT("symbol=" << m_contract.symbol));
it should read
LOG4CPLUS_TRACE(logger,
LOG4CPLUS_TEXT("symbol=") << m_contract.symbol);
instead.
As for the concatenated messages, what output layout are you using? If it is the pattern layout, then you should add the %n
formatter at the very end of the format string.
EDIT:
Unfortunately I am still getting the having the problem that the log messages are being concatenated. I think this has to do with the fact that the call request.toString() in the log message itself also has a call to a log message but for some reason the two messages are being printed together even after the code fix. :(
Ah, I misunderstood the problem, initially. So, you are logging a second event while you are preparing first. The issue is that the formatting is done to a thread-local ostringstream
. The thread-local ostringstream
is used as a performance enhancement. (The ostringstream
does not have to be constructed and destructed on each logged message.)
For immediate work around, you have two options. First, you stop this nested logging. Second, you "fix" LOG4CPLUS_*()
macros to not use the thread-local ostringstream
or you roll your own logging macros. Either should not be that hard.
Long term, I can add a special case to the logging macros that would make them use fresh ostringstream
each time to allow your use case.
EDIT 2:
I have filled a bug report and attached a patch that implements a work-around. See https://sourceforge.net/p/log4cplus/bugs/153/.
Upvotes: 2