文章转载自 https://blog.csdn.net/weixin_42542969/article/details/88836449
当写好的软件发布出去后,用户遇到死机或一些其他的bug,我们该怎么追踪这些问题呢,这时候日志系统很好的帮助了我们。
*我在原作者的基础上增加了日志输出模式的区分,开发阶段需要看到所有日志,而发布版只需要看错误日志就行了,所以在这里加以分别。
#define compileMode 2 //控制日志的输出模式: 1.debug; 2.release
void outputMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
static QMutex mutex;
mutex.lock();
QString text;
QString message;
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);
QFile file("log.txt");
file.open(QIODevice::WriteOnly | QIODevice::Append);
if(compileMode == 1){
switch(type){
case QtDebugMsg:
text = QString("Debug:");
message = QString("%1 %2 %3 %4").arg(text).arg(context_info).arg(msg).arg(current_date);
break;
case QtWarningMsg:
text = QString("Warning:");
message = QString("%1 %2 %3 %4").arg(text).arg(context_info).arg(msg).arg(current_date);
break;
case QtCriticalMsg:
text = QString("Critical:");
message = QString("%1 %2 %3 %4").arg(text).arg(context_info).arg(msg).arg(current_date);
break;
case QtFatalMsg:
text = QString("Fatal:");
message = QString("%1 %2 %3 %4").arg(text).arg(context_info).arg(msg).arg(current_date);
break;
}
}
else if(compileMode == 2){
switch(type){
case QtCriticalMsg:
text = QString("Critical:");
message = QString("%1 %2 %3 %4").arg(text).arg(context_info).arg(msg).arg(current_date);
break;
case QtFatalMsg:
text = QString("Fatal:");
message = QString("%1 %2 %3 %4").arg(text).arg(context_info).arg(msg).arg(current_date);
break;
}
}
if(message != ""){
QTextStream text_stream(&file);
text_stream << message << "\r\n";
file.flush();
file.close();
}
mutex.unlock();
}