wx中输出日志到文件

Coordinator
Jan 23, 2009 at 7:22 AM

Avoid long messages in the static wxLog functions.

(Don't know where the error comes from but wxLogFrame doesn't display long multiline error messages correctly. The reason for someone to use long messages might be the bad performance of wxTextControl::AppendText, which I think is GTK specific. -- Sascha Doerdelmann)

Example of sending messages to a log file for both release and debug versions

if (m_pLogFile == NULL)
{
   m_pLogFile = fopen( "log.txt", "w+" );
   delete wxLog::SetActiveTarget(new wxLogStderr(m_pLogFile));
}
wxLogMessage("Test");

When you close your program you would call:

delete wxLog::SetActiveTarget(NULL);
if (m_pLogFile != NULL)
{
	fclose(m_pLogFile);
}

Note that you must put the new target on the heap when you call SetActiveTarget and you must delete the return value (which is the old target). Also, you must use wxLogMessage for release builds. Normally this sends the message to a messagbox, but since you changed the target it won't. You could also force messages to go to stderr by doing this:

delete wxLog::SetActiveTarget(new wxLogStderr(NULL));