之前:qDebug()等调试信息。 缺点:没有行号和函数名等调试当项目调试输出特别多时,容易混乱 不知道是那里输出的调试信息。
现在:将行号,文件名,函数名,组合一体之后再输出信息。一目了然就能知道此信息在哪里输出。
#define qdebug qDebug()<<"["<<__FILE__<<":"<<__LINE__<<Q_FUNC_INFO<<"]"<<":"
debughelper.h
#ifndef COMMONHELPER_H
#define COMMONHELPER_H
#include <QFile>
#include <QDebug>
//调试所用宏
#define xdebug (QDebug(QtDebugMsg).nospace() << \
"Debug: [" << __LINE__ << " @" << Q_FUNC_INFO /*<< " @" << __FILE__*/ << "] MSG:").space()
#define zdebug(...) (QDebug(QtDebugMsg) \
<< "Debug: " << __VA_ARGS__ ).nospace() << '[' << Q_FUNC_INFO << " @" << __FILE__ << '(' << __LINE__ << ")]";
#define xinfo (QDebug(QtInfoMsg).nospace() << \
"Info: [" << __LINE__ << " @" << Q_FUNC_INFO << " @" << __FILE__ << "] MSG:").space()
#define zinfo(...) (QDebug(QtInfoMsg) \
<< "Info: " << __VA_ARGS__ ).nospace() << '[' << Q_FUNC_INFO << " @" << __FILE__ << '(' << __LINE__ << ")]";
#define xwarning (QDebug(QtWarningMsg).nospace() << \
"Warning: [" << __LINE__ << " @" << Q_FUNC_INFO << " @" << __FILE__ << "] MSG:").space()
#define zwarning(...) (QDebug(QtWarningMsg) \
<< "Warning: " << __VA_ARGS__ ).nospace() << '[' << Q_FUNC_INFO << " @" << __FILE__ << '(' << __LINE__ << ")]";
#define xcritical (QDebug(QtCriticalMsg).nospace() << \
"Critical: [" << __LINE__ << " @" << Q_FUNC_INFO << " @" << __FILE__ << "] MSG:").space()
#define zcritical(...) (QDebug(QtCriticalMsg) \
<< "Critical: " << __VA_ARGS__ ).nospace() << '[' << Q_FUNC_INFO << " @" << __FILE__ << '(' << __LINE__ << ")]";
//注意使用fatal会使程序终止
#define xfatal (QDebug(QtFatalMsg).nospace() << \
"Fatal: [" << __LINE__ << " @" << Q_FUNC_INFO << " @" << __FILE__ << "] MSG:").space()
#define zfatal(...) (QDebug(QtFatalMsg) \
<< "Fatal: " << __VA_ARGS__ ).nospace() << '[' << Q_FUNC_INFO << " @" << __FILE__ << '(' << __LINE__ << ")]";
#endif // COMMONHELPER_H
#
另一种方法(不改变qDebug() 等原来的语法)
新建一个名字为TestApp的应用。代码如下:
#include <QCoreApplication>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
qSetMessagePattern("%{appname} %{type} %{time [yyyy-MM-dd hh:mm:ss]} %{file} %{line} %{function} %{message}");
qInfo() << "Hello world";
qDebug() << "Hello world";
qWarning() << "Hello world";
return a.exec();
}
输出:
TestApp info [2020-04-13 23:01:11] …\TestApp\main.cpp 8 main Hello world
TestApp debug [2020-04-13 23:01:11] …\TestApp\main.cpp 9 main Hello world
TestApp warning [2020-04-13 23:01:11] …\TestApp\main.cpp 10 main Hello world
通过设置qSetMessagePattern函数去更改默认的消息。一般常用的格式字符串有:
注意:
qSetMessagePattern从Qt 5.0引入。
只能打印Qt的调试输出如:qDebug,qInfo,qWarning,qCritical,qFatal。而printf,cout将会原样输出。