After searching around for a reason that qDebug() statements work fine with Qt's standard message handler but fail when I switch to my own, I'm appealing here to see if anyone else has any experience with the problem.
Things I know about / have tried, that do nothing...
1) CONFIG += console
2) DEFINES -= QT_NO_WARNING_OUTPUT QT_NO_DEBUG_OUTPUT
3) ::fprintf(stderr, "ERROR\n"); ::fflush(stderr);
4) ::fprintf(stdout, "OUTPUT\n"); ::fflush(stdout);
5) std::cerr << "CERROR" << std::endl; std::cerr.flush();
However it works correctly when using the built in handler (ie it prints the message to the QtCreator console)
int main(int argc, char *argv[]) {
// Use my handler
qInstallMessageHandler(MyCustomLogger);
qDebug() << "Not Printed";
// Use standard handler
qInstallMessageHandler(0);
qDebug() << "Correctly Printed";
// Use my handler again
qInstallMessageHandler(MyCustomLogger);
qDebug() << "Not Printed Again...";
}
The most recent test was allocating myself a console using WinAPI commands this results in the correct behavior all output to stderr and stdout are visible on the console I created. However, this is not the behavior I want, I want to be able to view this output in QtCreator.
Any thoughts on how the standard message handler prints to the debugger? I've not managed to find it in the Qt sources yet.
As Frank Osterfeld mentioned in his comment:
On windows, qDebug() uses the debug channel, not stderr.
After delving into the QDebug code and QMessageLogger I've found my answer. The handy WinAPI function OutputDebugString
.
Usage (Modified from peppe's):
#include <QApplication>
#include <QtDebug>
#include <QtGlobal>
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
void MyMessageOutput(QtMsgType Type, const QMessageLogContext& Context, const QString &Message)
{
OutputDebugString(reinterpret_cast<const wchar_t *>(Message.utf16()));
}
int main(int argc, char **argv)
{
// A GUI application
QApplication app(argc, argv);
// Custom handler
qInstallMessageHandler(myMessageOutput);
qDebug() << "Printed in the console using my message handler in a windows GUI application";
// Default handler
qInstallMessageHandler(0);
qDebug() << "Also printed in the console!";
// Show GUI here
//MainForm *MF = new MainForm();
//MF->show();
return app.exec();
}