qInstallMsgHandler實現日志輸出


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

#define _TIME_ qPrintable (QTime::currentTime ().toString ("hh:mm:ss:zzz"))

void Log(QtMsgType type, const char* msg)
{
    QString qstrText;
    switch (type)
    {
    case QtDebugMsg:
        qstrText = QString("%1: %2").arg(_TIME_, msg);
        break;
    case QtWarningMsg:
        qstrText = QString("%1: %2").arg(_TIME_, msg);
        break;
    case QtCriticalMsg:
        qstrText = QString("%1: %2").arg(_TIME_, msg);
        break;
    case QtFatalMsg:
        qstrText = QString("%1: %2").arg(_TIME_, msg);
        exit(0);
    }
    QFile out("log.txt");
    out.open(QIODevice::WriteOnly | QIODevice::Append);
    QTextStream ts(&out);
    ts<<qstrText<<endl;
}

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

    qInstallMsgHandler(Log);

    qDebug("this is a debug message");
    qWarning("this is a warning message");
    qCritical("this is a critical message");
    qFatal("this is a fatal message");

    return a.exec();
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM