在qt的使用过程中,开发者通常使用qDebug, qInfo, qWarning输出控制台信息。且qt提供直接通过qDebug等方法将信息输出到文本文件的方法。又因为qDebug本身线程安全,因此在使用的过程中能够减少开发者在多线程数据处理的负担。
关于将qDebug信息重定向到文本的示例如下:
void writeToLog(QtMsgType type, const QMessageLogContext &context, const QString &msg) {
QString prefix;
switch (type) {
case QtDebugMsg:
prefix = "Debug";
break;
case QtInfoMsg:
prefix = "Info";
break;
case QtWarningMsg:
prefix = "Warning";
break;
case QtCriticalMsg:
prefix = "Critical";
break;
case QtFatalMsg:
prefix = "Fatal";
break;
}
QString fileName = "run_" + QDateTime::currentDateTime().toString("yyyyMMdd") + ".log";
QFile logFile(QApplication::applicationDirPath() + LOG + fileName);
if (logFile.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text))
{
QTextStream out(&logFile);
out << "[" << QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz") << "] "
<< "[" << prefix << "] "
<< context.category << ": "
<< msg << " (" << context.file << ":" << context.line << ")\n";
logFile.close();
}
// 对于QtFatalMsg,确保标准处理被执行(默认是终止程序)
if (type == QtFatalMsg)
abort();
}
int main(int argc, char **argv) {
QApplication a(argc, argv);
qInstallMessageHandler(writeToLog);
// TODO: 初始化自己的窗口或进行其他操作
return QApplication::exec();
}