软件设计,常需要监测软件的软件的运行情况,用来记录软件运行情况,并在出现问题是辅助查找问题。
基于qt的软件设计,设计中常使用qDebug()来打印相关内容。下文介绍如何将打印内容输出到指定的文件。
主要使用到了qInstallMessageHandler函数。代码如下:
void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
QByteArray localMsg = msg.toLocal8Bit();
QString txtMessage;
switch (type) {
case QtDebugMsg:
txtMessage = QString("Debug:%1").arg(msg);
break;
case QtInfoMsg:
txtMessage = QString("Info File:%1 %2 Line:%3 Content:%4").arg(context.file).arg(context.function).arg(context.line).arg(msg);
break;
case QtWarningMsg:
txtMessage = QString("Warning File:%1 %2 Line:%3 Content:%4").arg(context.file).arg(context.function).arg(context.line).arg(msg);
break;
case QtCriticalMsg:
txtMessage = QString("Critical File:%1 %2 Line:%3 Content:%4").arg(context.file).arg(context.function).arg(context.line).arg(msg);
break;
case QtFatalMsg:
txtMessage = QString("Fatal File:%1 %2 Line:%3 Content:%4").arg(context.file).arg(context.function).arg(context.line).arg(msg);
abort();
}
//保存输出相关信息到指定文件
QFile outputFile("customMessageLog.txt");
outputFile.open(QIODevice::WriteOnly | QIODevice::Append);
QTextStream textStream(&outputFile);
textStream << txtMessage <<endl;
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
qInstallMessageHandler(myMessageOutput); //注册MsgHandler回调函数
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}