好久没更新了,这次介绍 qDebug()的所有输出转移至文件中

哎哎8年前 (2015-11-20)C++3750
#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;
    out.close();
}
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();
}


这种方法,可以防止信息过大,qtcreate 崩溃,但是会很浪费cpu 假如你的输出很多的话。

我的一个抓包程序 竟然占用25% 进行写入。


另外一种想法可能是 不停打开文件,关闭文件导致cpu占用过高。

然后变形如下:

#include <QtDebug>
#include <QFile>
#include <QTextStream>
#define _TIME_ qPrintable (QTime::currentTime ().toString ("hh:mm:ss:zzz"))
  QFile out("log.txt");
  
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);
    }
  
    
    QTextStream ts(&out);
    ts<<qstrText<<endl;

}
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    //构造函数中添加
    out.open(QIODevice::WriteOnly | QIODevice::Append);
    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");
      out.close();
    return a.exec();
}

析构函数中添加:
    out.close();


相关文章

[QT]qt 程序退出代码。

  1.关闭主窗口并退出程序是    QApplication::exit()     2.如果是QDialog,就accept() 或 reje...