在工作中要打印qDebug信息和终端窗口中的警告信息,方便进行问题追踪和调试。
直接上测试代码:
void MyMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
QString logText;
// 选择日志级别,并构造日志文本
switch (type) {
case QtDebugMsg:
logText = QString("[Debug]%1").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")+ ":" + msg);
break;
case QtInfoMsg:
logText = QString("[Info]%1").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")+ ":" + msg);
break;
case QtWarningMsg:
logText = QString("[Warning]%1").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")+ ":" + msg);
break;
case QtCriticalMsg:
logText = QString("[Critical]%1").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")+ ":" + msg);
break;
case QtFatalMsg:
logText = QString("[Fatal]%1").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")+ ":" + msg);
break;
default:
break;
}
// 写入日志文件
QFile logFile("./debug.txt");
logFile.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text);
QTextStream textStream(&logFile);
textStream << logText << endl;
logFile.close();
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
qInstallMessageHandler(MyMessageOutput);
//多线程测试
MyThread thread;
thread.Open();
thread.start();
return a.exec();
}
程序运行之后,在终端上将不会有输出信息。只有当程序异常退出之后,终端窗口上会有一个退出提示。运行结果如下:
参考链接:
QDebug 自定义信息输出到文件_qdebug输出到文件-CSDN博客https://blog.csdn.net/qq_41350775/article/details/131461124