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

哎哎9年前 (2015-11-20)C++4888
#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设计师,快速将 ACTIONS 放入toolbar中

使用QT设计师,快速将 ACTIONS 放入toolbar中

  网上很多例子,都是手动敲代码在Qt界面工具栏中插入Action,实际QTDesigner本身带有其功能,而且非常方便。  插入完界面后,我们还可以去看它生成的代码,了解一下如何手动插入工具栏按钮。...

客人宾馆如厕时马桶爆裂身受重伤 宾馆反要赔偿

客人宾馆如厕时马桶爆裂身受重伤 宾馆反要赔偿

    最近有一则奇闻,说的是一位住客在西安住酒店时,屁股被爆裂的马桶划伤,酒店怀疑他是站在马桶上大便压爆了马桶。而昨天,南京鼓楼法院也宣判了这样一起奇特的人身损害案件,王纬在南京某宾馆住宿如厕时,马...

解决QWidget: Cannot create a QWidget when no GUI is being used

  长时间不用Qt了,新建了个控制台工程再添加自己的类,即是不想使用designer来设计自己的界面,编译时没有错误,执行时出现QWidget: Cannot create a QWidget whe...

[QT]qt 程序退出代码。

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