Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 942
  • Last Modified:

Redirect cout to a log file for a CWinApp

I want to redirect the cout and cerr to a logfile for my application.
The following code works but only in InitInstance().
How do i make the redirect work for the entire app??

BOOL CDwgFilesApp::InitInstance()
{
//Create Runtime debug log
    std::ofstream logFile("c:\\IBitS\\tmp\\SDBSdwg.log");
    std::streambuf *outbuf = std::cout.rdbuf(logFile.rdbuf());
    std::streambuf *errbuf = std::cerr.rdbuf(logFile.rdbuf());
    std::cout << "SDBSdwg Runtime Debug Log\n\n";
}
else if (nResponse == IDCANCEL)
{
   // restore the buffers
    std::cout.rdbuf(outbuf);
    std::cerr.rdbuf(errbuf);
}

this does not work!!!!
BOOL CDwgFilesDlg::OnInitDialog()
{
  std::cout << "this is a test\n";
}
0
MCofer
Asked:
MCofer
  • 2
1 Solution
 
mnashadkaCommented:
The biggest issue here is that the logFile object goes out of scope after InitInstance (and so does the streambuf associated with it).  Add std::ofstream logFile; as a data member to your CDwgFileApp class, and call logFile.open("c:\\logfile.log"); in InitInstance, then it should work.  Good luck!
0
 
MCoferAuthor Commented:
Thanks
  It's working great (except)
  It creates the log file at InitInstance() but does not write anything until I cancel the App.
  Is there a way to make it write each time cout is called?
0
 
mnashadkaCommented:
If you call DoModal() inside your InitInstance, then the function will not return until the Ok or Cancel buttons are clicked (or equivalent commands).  You may want to do the cout's inside the dialog.  Also, if you're already doing this, try to insert flush to flush the data into the file, like:
std::cout << "This is my message" << std::endl << std::flush;

If you set the unitbuf flag (std::cout.setf(std::ios_base::unitbuf);), then it will flush every time you insert something into the stream.  I hope this helps.
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now