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?
This is wrong code
it should read
instead.
As for the concatenated messages, what output layout are you using? If it is the pattern layout, then you should add the
%nformatter at the very end of the format string.EDIT:
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-localostringstreamis used as a performance enhancement. (Theostringstreamdoes 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-localostringstreamor 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
ostringstreameach 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/.