1.安装消息处理程序qInstallMessageHandler
//自定义消息处理函数
void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
fprintf(stderr,"%s << ",context.category);
QByteArray localMsg = msg.toLocal8Bit();
switch (type) {
case QtDebugMsg:
fprintf(stderr, "Debug: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
break;
case QtInfoMsg:
fprintf(stderr, "Info: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
break;
case QtWarningMsg:
fprintf(stderr, "Warning: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
break;
case QtCriticalMsg:
fprintf(stderr, "Critical: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
break;
case QtFatalMsg:
fprintf(stderr, "Fatal: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
break;
}
}
int main(int argc, char *argv[])
{
if(1)
//安装消息处理函数
qInstallMessageHandler(myMessageOutput);
else
//更改默认消息处理程序的输出
qSetMessagePattern("[%{time yyyyMMdd h:mm:ss.zzz t} \
%{if-debug}D%{endif}\
%{if-info}I%{endif}\
%{if-warning}W%{endif}\
%{if-critical}C%{endif}\
%{if-fatal}F%{endif}] \
%{file}:%{line} - %{message}");
QApplication a(argc, argv);
QWidget w;
w.show();
return a.exec();
}
2.使用QLoggingCategory启用或禁用log输出
.h文件
//widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QLoggingCategory>
// in a header
Q_DECLARE_LOGGING_CATEGORY(WidgetLog)
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
private:
Ui::Widget *ui;
};
#endif // WIDGET_H
.cpp文件
#include "widget.h"
#include "ui_widget.h"
Q_LOGGING_CATEGORY(WigetLog, "WigetLog")
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
qCDebug(WigetLog) << "a debug message";
//使用setFilterRules启用或禁用log输出
QLoggingCategory::setFilterRules("WigetLog.debug=false");
//QLoggingCategory::setFilterRules("WigetLog.*=false");
//QLoggingCategory::setFilterRules("*.debug=false");
//QLoggingCategory::setFilterRules("*=true");
qCDebug(WigetLog) << "a debug message";
qCInfo(WigetLog) << "a debug message";
qDebug() << "abcdset";
}
Widget::~Widget()
{
delete ui;
}
3.使用配置文件QT_LOGGING_CONF宏
在工程的.pro中添加
QT_LOGGING_CONF=./logconfig.ini
logconfig.ini文件
[Rules]
*=false
WigetLog.debug=true