How to redirect qDebug output to a file

From Qt Wiki
Jump to navigation Jump to search

Template:ArticleMetaData

In Qt the default message handler function prints debug messages, warnings, critical and fatal error messages to standard output or to the debugger. If you wish to get more control over message handling you need to implement your own message handler and register your message handler by calling qInstallMsgHandler(yourHandlerFunction).


  1. include <QtDebug>
  2. include <QFile>
  3. include <QTextStream>

void customMessageHandler(QtMsgType type, const char *msg) { QString txt; switch (type) { case QtDebugMsg: txt = QString("Debug: %1").arg(msg); break;

case QtWarningMsg: txt = QString("Warning: %1").arg(msg); break; case QtCriticalMsg: txt = QString("Critical: %1").arg(msg); break; case QtFatalMsg: txt = QString("Fatal: %1").arg(msg); abort(); }

QFile outFile("debuglog.txt"); outFile.open(QIODevice::WriteOnly | QIODevice::Append); QTextStream ts(&outFile); ts << txt << endl; }

int main( int argc, char * argv[] ) { QApplication app( argc, argv );

//Lets register our custom handler, before we start qInstallMsgHandler(customMessageHandler); ... return app.exec(); }


  • Now output of a call to qDebug() redirects to debug-log file specified in the customMessageHandler.