1

I have written a class to log messages in my application. The class has the options to either log to console, log to file or both.

A thread monitors a queue of strings, if the queue is empty. When I process a string to log to file:

if ( (blnOpen = clsDebugService::msFile.isOpen()) != true ) {
  clsDebugService::msFile.open(QIODevice::WriteOnly | QIODevice::Text);
  blnOpen = clsDebugService::msFile.isOpen();
}
if ( blnOpen == true ) {
  QTextStream tsText(&clsDebugService::msFile);
  tsText << strLine.toLatin1().data() << "\r\n";
}

This works perfectly and I can see that the information logged in the file is always complete, however when I do the following to output to the console:

if ( clsDebugService::msblnToConsole == true ) {
  std::cout << strLine.toLatin1().data() << "\n";
  std::cout << std::flush;
}

Sometimes, actually quite frequently the message displayed in the console isn't complete and is missing some characters from the end of the string. Originally I had the std::flush at the end of the same statement that sends the data to the console, this did the same, so I changed it to the above hoping that would fix it, it didn't.

SPlatten
  • 5,334
  • 11
  • 57
  • 128
  • Maybe you have already read this post, not sure it corresponds to your problem exactly. However, the C++20 `std::osyncstream` wrapper seems interesting. https://stackoverflow.com/questions/14718124/how-to-easily-make-stdcout-thread-safe – Damien Oct 14 '20 at 14:30

1 Answers1

0

So, it looks that std::flush doesn't wait for previous statement to complete? Can you try something like std::cout.setf(std::ios::unitbuf);. and see if that helps. (Not like I recommend that from performance point of view). (This may obsolete need of std::flush as well).

noonex
  • 1,975
  • 1
  • 16
  • 18
  • Thank you, unfortunately it didn't fix the issue and I'm still missing data from the Application Output ( stdout ), yet the file log is complete. – SPlatten Oct 15 '20 at 06:07