Qt4实现将调试信息保存到日志

#include <QtDebug>
#include <QFile>
#include <QTextStream>

void customMessageHandler(QtMsgType type, const char *msg)
{
        QString txt;
        switch (type) {
        //调试信息提示
        case QtDebugMsg:
                txt = QString("Debug: %1").arg(msg);
                break;

        //一般的warning提示
        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 );

        //先注册自己的MsgHandler
        qInstallMsgHandler(customMessageHandler);        
        
        //以后就可以像下面这样直接打日志到文件中,而且日志也会包含时间信息
        qDebug("This is a debug message at thisisqt.com");
        qWarning("This is a warning message  at thisisqt.com");
        qCritical("This is a critical message  at thisisqt.com");
        qFatal("This is a fatal message at thisisqt.com");

        return app.exec();
}


Qt4实现将调试信息保存到日志_第1张图片


你可能感兴趣的:(qt,include)