在arm板上运行qt程序的时候,调试方法除了生成core文件,gdb和串口调试外还可以通过查看输出日志文件定位bug,这样省去了接串口和操作gdb的麻烦,如果代码中有充分的log输出,通过log信息定位bug是相对简单快速的方法,下面简单介绍qt如何生成log文件
-
注册消息函数
在main函数创建窗口之前注册消息函数:
注册消息后,代码中的log信息(如qDebug(),qWarning()等)会输出到相应log文件
例:qInstallMessageHandler(logMessage);
-
消息函数体
其中msgType为消息类型,其值可以为:QtDebugMsg, QtWarningMsg, QtCriticalMsg, QtFatalMsg, QtInfoMsg, QtSystemMsg其中之一,msgContext为消息附带信息,可以用于定位触发消息的位置,msgText为消息体,即具体的消息内容
例:输出log文件mssageLog.txtvoid logMessage(QtMsgType msgType, const QMessageLogContext &msgContext, const QString &msgText) { static QMutex mutex; mutex.lock(); //组建消息log QString res_msg = QString("%1 %2:%3 type %4: %5")\ .arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"))\ .arg((QString(msgContext.file).split("/")).last())\ .arg(msgContext.line)\ .arg(msgType)\ .arg(msgText); QFile logfile("mssageLog.txt"); logfile.open(QIODevice::WriteOnly | QIODevice::Append); QTextStream logStream(&logfile); logStream<<res_msg<<"\r\n"; logfile.flush(); logfile.close(); mutex.unlock(); }
-
测试输出log文件
//log测试 qDebug("This is a debug message"); qWarning("This is a warning message");
-
测试结果
注:对于release版本在pro文件中加上:DEFINES += QT_MESSAGELOGCONTEXT