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

QT关于程序运行日志

2017-08-24 14:13 246 查看
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 ddd");
QString current_date = QString("(%1)").arg(current_date_time);
QString message = QString("%1 %2 %3 %4").arg(text).arg(context_info).arg(msg).arg(current_date);

QFile file("log.txt");
file.open(QIODevice::WriteOnly | QIODevice::Append);
QTextStream text_stream(&file);
text_stream << message << "\r\n";
file.flush();
file.close();
mutex.unlock();
}

main函数中添加;

qInstallMessageHandler(outputMessage);

//这样就在程序的当前目录建立了log.txt记录程序运行的日志

//注意,Qmessagebox事件会被锁住
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: