qDebug 输出重定向

时间:2021-11-19 19:25:33

把qDebug()<<的输出重定向到文件debuglog.txt上。。并且设置了输出的格式为:时间+输出内容+换行;

#include <QDebug>

#include <QFile>

#include <QDabeTime>

void customMessageHandler(QtMsgType type, const char *msg)
{
    QString txt;
    switch (type)
    {
    case QtDebugMsg:
        txt = QString(" %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();
    }
    QTime l_time = QTime::currentTime();
    QDate l_Date = QDate::currentDate();
    QString l_strDate = l_Date.toString("MM.dd");
    QString l_strTime = l_time.toString("hh:mm:ss");
    l_strDate.append(" ");
    l_strDate.append(l_strTime);
    QFile outFile("debuglog.txt");
    outFile.open(QIODevice::WriteOnly | QIODevice::Append);
    QTextStream ts(&outFile);
    ts << l_strDate<< " " << txt << endl;
}

 

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    qInstallMsgHandler(customMessageHandler);

。。。。。