qt之输出日志到文件中

qt之输出日志到文件中

 

描述
    助手中在C++ API changes中提到:Qt::qDebug()、Qt::qWarning()、Qt::qCritical()、Qt::qFatal()被改变为宏来跟踪源代码的消息来源。被打印的信息可以被配置(用于缺省消息处理程序),通过设置该新的环境变量QT_MESSAGE_PATTERN。Qt::qInstallMsgHandler()已过时,因此建议使用Qt::qInstallMessageHandler()来代替。
 
级别
qDebug:调试信息
qWarning:警告信息
qCritical:严重错误
qFatal:致命错误
 
   
需求(目的):生成log.txt日志文件,记录详细日志信息(包括等级、所在文件、所在行号、描述信息、产生时间等),以便于快速跟踪、定位。
  下述代码

 

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(current_date).arg(msg);

 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();
}


int main(int argc, char *argv[])
{
 QApplication a(argc, argv);
 QtGuiApplication1 w;
 w.show();


 qInstallMessageHandler(outputMessage);

 string ss = "nihao";
 int a = 18;
 qDebug("This is a debug message");
 qDebug() << ss.c_str() << a << endl;
 qWarning("This is a warning message");
 qCritical("This is a critical message");
 //qFatal("This is a fatal message");
 return a.exec();
}

 

 

输出结果:

Debug: File:(QtGuiApplication1.cpp) Line:(72) (2017-08-28 15:59:41 周一) This is a debug message
Debug: File:(QtGuiApplication1.cpp) Line:(73) (2017-08-28 15:59:41 周一) nihao 18

Warning: File:(QtGuiApplication1.cpp) Line:(74) (2017-08-28 15:59:41 周一) This is a warning message
Critical: File:(QtGuiApplication1.cpp) Line:(75) (2017-08-28 15:59:41 周一) This is a critical message
Warning: File:(kernel\qobject.cpp) Line:(246) (2017-08-28 15:59:42 周一) QObject::~QObject: Timers cannot be stopped from another thread

你可能感兴趣的:(QT)