Qt 项目运行日志

在使用Qt的时候,如果代码出bug了,可以查看应用程序输出的内容,查看bug的位置和说明。但是把项目打包成exe可运行程序以后,就无法查看输出内容了,需要使用日志系统。

日志系统的核心步骤是:重写消息处理函数具体定义,从而把系统的输出内容保存到指定的文件中。代码如下

#include 
#include 
#include 
#include 
#include 


// 重写消息处理函数具体定义
void MainWindow::myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    QString currentDateTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    QString logFileName = QCoreApplication::applicationDirPath() + "/log.txt";
    QFile file(logFileName);
    file.open(QIODevice::WriteOnly | QIODevice::Append);
    QTextStream stream(&file);
    switch (type) {
    case QtDebugMsg:
        stream << currentDateTime << " Debug: " << msg << " (" << context.file << ":" << context.line << ")\n";
        break;
    case QtInfoMsg:
        stream << currentDateTime << " Info: " << msg << " (" << context.file << ":" << context.line << ")\n";
        break;
    case QtWarningMsg:
        stream << currentDateTime << " Warning: " << msg << " (" << context.file << ":" << context.line << ")\n";
        break;
    case QtCriticalMsg:
        stream << currentDateTime << " Critical: " << msg << " (" << context.file << ":" << context.line << ")\n";
        break;
    case QtFatalMsg:
        stream << currentDateTime << " Fatal: " << msg << " (" << context.file << ":" << context.line << ")\n";
        abort();
    }
    file.close();
}

注意使用上述函数前,要在主进程里面加入这一句(加在哪都行,只要能保证代码在执行时能执行到这一句,最好加载运行时的最前面):

qInstallMessageHandler(myMessageOutput);

这样就完成了。

你可能感兴趣的:(qt,开发语言)