开发过程中写日志文件是必不可少
Qt中自带qInstallMessageHandler来进行日志的收集
使用方法
第一步:设置qInstallMessageHandler的回调函数:
#include "CsdnDemo.h"
#include <QApplication>
#include<QTranslator>
#include<QDateTime>
#include<QMutex>
#include<QFile>
#include<QTextStream>
//日志文件名称
#define LOG_FILE qApp->applicationDirPath()+"/logger.txt"
//日志收集回调函数
void MessageOutPut(QtMsgType type, const QMessageLogContext &context, const QString &msg);
int main(int argc, char *argv[])
{
qInstallMessageHandler(MessageOutPut);
QApplication a(argc, argv);
CsdnDemo w;
w.show();
return a.exec();
}
void MessageOutPut(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:");
break;
default:
break;
}
//日志写到文件
QString current_date_time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
QString message = QString("%1 %2%3").arg(current_date_time).arg(text).arg(msg);
QFile file(LOG_FILE);
file.open(QIODevice::WriteOnly | QIODevice::Append);
QTextStream text_stream(&file);
text_stream << message << "\r\n";
file.flush();
file.close();
mutex.unlock();
}
第二步调用:
例如:
#ifndef CONFIG_H
#define CONFIG_H
#include<QDebug>
#define xPrint qDebug()<<__FUNCTION__<<"["<<__LINE__<<"]"
#define xErrPrint qCritical()<<__FUNCTION__<<"["<<__LINE__<<"]"
#endif // CONFIG_H
#include "CsdnDemo.h"
#include "ui_CsdnDemo.h"
#include"config.h"
#include<QFile>
#pragma execution_character_set("utf-8")
CsdnDemo::CsdnDemo(QWidget *parent) :
QWidget(parent),
ui(new Ui::CsdnDemo)
{
ui->setupUi(this);
load("test.txt");
}
void CsdnDemo::load(const QString fileName)
{
QFile file(fileName);
xPrint<<fileName;
if (!file.exists()){
xErrPrint<<QString("File '%1' does not exist!").arg(fileName);
}
}
运行结果会在指定日志路径下生成looger.txt
内容为