Live & Learn
分类: LINUX
2015-08-27 11:49:24
#include <QtDebug>
#include <QFile>
#include <QTextStream>
#define _TIME_ qPrintable (QTime::currentTime ().toString ("hh:mm:ss:zzz"))
void Log(QtMsgType type, const char* msg) { QString qstrText; switch (type) { case QtDebugMsg: qstrText = QString("%1: %2").arg(_TIME_, msg); break; case QtWarningMsg: qstrText = QString("%1: %2").arg(_TIME_, msg); break; case QtCriticalMsg: qstrText = QString("%1: %2").arg(_TIME_, msg); break; case QtFatalMsg: qstrText = QString("%1: %2").arg(_TIME_, msg); exit(0); } QFile out("log.txt"); out.open(QIODevice::WriteOnly | QIODevice::Append); QTextStream ts(&out); ts<<qstrText<<endl; } int main(int argc, char *argv[]) { QApplication a(argc, argv); qInstallMsgHandler(Log); qDebug("this is a debug message"); qWarning("this is a warning message"); qCritical("this is a critical message"); qFatal("this is a fatal message"); return a.exec(); }
//=========================================================
使用qInstallMsgHandler将日志保存到文件
1 在main函数之前定义回调函数
void myMessageOutput(QtMsgType type, const char *msg)
{
QString text;
switch (type)
{
case QtDebugMsg:
text = QString("Debug: %1").arg(msg);
break;
case QtWarningMsg:
text = QString("Warning: %1").arg(msg);
break;
case QtCriticalMsg:
text = QString("Critical: %1").arg(msg);
break;
case QtFatalMsg:
text = QString("Fatal: %1").arg(msg);
abort();
}
QFile file("111.txt");
file.open(QIODevice::WriteOnly | QIODevice::Append);
QTextStream ts(&file);
ts<<text<<endl;
}
2 在main函数中注册myMessageOutput
qInstallMsgHandler(myMessageOutput);
3 注册后,在该程序的任何地方使用即可。
qDebug("This is a debug message");
qWarning("This is a warning message");
qCritical("This is a critical message");
qFatal("This is a fatal message");
posted on 2011-03-22 17:25 seahouse 阅读(1056) 评论(0) 编辑 收藏 引用 所属分类: Qt