Qt提供了qInstallMsgHandler 方法用来定制消息发生后如何来处理。
qInstallMsgHandler 是一个回调函数,主要是由qDebug、qWarnng、qCritical、qFatal这些函数进行触发,
也就是说,qDeubg这些函数处理的消息文本会被qInstallMsgHandler 所指向的回调函数截获,这样就允许用户自己来处理这些消息文本。
例如,你完全可以将这些消息文本输出并保存到相关的日志文件中。请看下面的示例!
qDebug : 调试信息提示
qWarning: 一般的警告提示
qCritical: 严重错误提示
qFatal: 致命错误提示
注意,release版本的日志中QMessageLogContext内容为空,解决方案请参考
在pro文件中添加一个定义:
DEFINES += QT_MESSAGELOGCONTEXT
|
qDebug() << "hello from worker thread " << thread()->currentThreadId();
qDebug()<<"Value is "<<c; qInfo()<<"INFO VALUE is"; qCritical()<<"qWarning"; qFatal("fatal error"); qDebug()<<"Value is "<<c;
|
qt5
void outputMessage(QtMsgType type,const QMessageLogContext& context, const QString& msg) { static QMutex mutex; mutex.lock();
QString text; switch (type) { case QtDebugMsg: text = QString("Debug:"); break;
case QtWarningMsg: text = QString("Warning:"); break;
case QtCriticalMsg: text = QString("Critical:"); break;
case QtFatalMsg: text = QString("Fatal:"); }
QString context_info = QString("File:(%1) Line:(%2)").arg(QString(context.file)).arg(context.line); QString current_date_time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss:zzz"); QString message = QString("%1 %2 %3 %4").arg(current_date_time).arg(text).arg(context_info).arg(msg);
QDir dir; QString currentPath = QApplication::applicationFilePath(); currentPath += "/comHelper.log"; QFile file(currentPath); file.open(QIODevice::WriteOnly | QIODevice::Append); QTextStream text_stream(&file); text_stream << message << "\r\n"; file.flush(); file.close();
mutex.unlock(); }
qInstallMessageHandler(outputMessage); qDebug("comHelper started...");
|
qt4
void outputMessage(QtMsgType type, const char *msg) { static QMutex mutex; mutex.lock();
QString text; switch(type) { case QtDebugMsg: text = QString("Debug:"); break;
case QtWarningMsg: text = QString("Warning:"); break;
case QtCriticalMsg: text = QString("Critical:"); break;
case QtFatalMsg: text = QString("Fatal:"); }
QString current_date_time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss:zzz"); QString message = QString("%1 %2 %3").arg(current_date_time).arg(text).arg(msg);
QDir dir; QString currentPath = dir.currentPath(); currentPath += "/remoteCom.log"; QFile file(currentPath); file.open(QIODevice::WriteOnly | QIODevice::Append); QTextStream text_stream(&file); text_stream << message << "\r\n"; file.flush(); file.close();
mutex.unlock(); }
qInstallMsgHandler(outputMessage);
qDebug("remoteCom started...");
QString strLog = "param=" + param; qDebug(strLog.toLatin1().data());
|