您的位置:首页 > 编程语言 > Qt开发

Qt4使用qInstallMsgHandler函数往控制台和文件中写入日志

2018-01-23 15:06 1331 查看
qInstallMsgHandler 函数原型:QtMsgHandler qInstallMsgHandler(QtMsgHandler);

QtMsgHandler函数指针原型:  typedef void( * QtMsgHandler)(QtMsgType, const char *);

qInstallMsgHandler用于自定义日志消息函数,下面是用法:

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

class Widget : public QWidget
{
Q_OBJECT

public:
Widget(QWidget *parent = 0);
~Widget();
};

#endif // WIDGET_H
widget.cpp
#include "widget.h"

Widget::Widget(QWidget *parent)
: QWidget(parent)
{
resize(800, 480);
}

Widget::~Widget()
{

}
main.cpp
#include "widget.h"
#include <QApplication>
#include <QFile>
#include <QTextStream>
#include <QDebug>

void myMessageOutput(QtMsgType type, const char *msg)
{
/* 往控制台中打印 */
switch (type)
{
case QtDebugMsg:
fprintf(stderr, "%s\n", msg);
break;
case QtWarningMsg:
fprintf(stderr, "Warning: %s\n", msg);
break;
case QtCriticalMsg:
fprintf(stderr, "Critical: %s\n", msg);
break;
case QtFatalMsg:
fprintf(stderr, "Fatal: %s\n", msg);
abort();
}

/* 输出到文件 */
QString txt;
switch (type) {
case QtDebugMsg:
txt = QString("Debug: %1\n").arg(msg);
break;

case QtWarningMsg:
txt = QString("Warning: %1\n").arg(msg);
break;
case QtCriticalMsg:
txt = QString("Critical: %1\n").arg(msg);
break;
case QtFatalMsg:
txt = QString("Fatal: %1\n").arg(msg);
abort();
}

QFile outFile("debug.log");
outFile.open(QIODevice::WriteOnly | QIODevice::Append);
QTextStream ts(&outFile);
ts << txt << endl;
}

int main(int argc, char *argv[])
{
qInstallMsgHandler(myMessageOutput);
QString setscheduler = QString("renice -20 %1").arg(getpid());
qDebug() << "getpid = " << getpid();
qDebug() << "hello, world!";
qWarning() << "this is a warning!";
qCritical("This is a critical message");
qFatal("This is a fatal message");
system(qPrintable(setscheduler));
QApplication a(argc, argv);
Widget w;
w.show();

return a.exec();
}


交叉编译到开发板运行,可以看到控制台输出自定义的日志,当前工作目录下生成相应的日志文件:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐