发现前面只写了大概的log的逻辑而没有贴上代码,这里补上代码吧
. h的代码
#include <QObject>
class QmlLog4Qml : public QObject
{
Q_OBJECT
public:
QmlLog4Qml();
Q_INVOKABLE void qDebug_Info(int type, QString strInfo);
};
. cpp代码
/*!
*@file QmlLog4Qml.cpp
*@brief Qml写日志
*@version 1.0
*@section LICENSE Copyright (C) 2003-2103 CamelSoft Corporation
*@author zhengtianzuo
*/
#include "QmlLog4Qml.h"
#include <QMutex>
#include <QFile>
#include <QDateTime>
#include <QTextStream>
void outputMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
static QMutex mutex;
mutex.lock();
QString text;
QString message = "";
switch(type)
{
case QtDebugMsg: {
text = QString("Debug:");
if (context.file != nullptr)
{
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);
message = QString("%1 %2 %3 %4").arg(text).arg(context_info).arg(msg).arg(current_date);
}
else
{
message = msg;
}
QFile file("configlog.txt");
file.open(QIODevice::WriteOnly | QIODevice::Append);
QTextStream text_stream(&file);
text_stream << message << "\r\n";
file.flush();
file.close();
}
break;
case QtCriticalMsg: {
if (context.file != nullptr)
{
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);
message = QString("%1 %2 %3 %4").arg(msg).arg(current_date);
}
else
{
message = msg;
}
QFile file("templog.txt");
file.open(QIODevice::WriteOnly | QIODevice::Append);
QTextStream text_stream(&file);
text_stream << message << "\r\n";
file.flush();
file.close();
}
break;
}
mutex.unlock();
}
QmlLog4Qml::QmlLog4Qml()
{
qInstallMessageHandler(outputMessage);
}
void QmlLog4Qml::qDebug_Info(int type, QString strInfo)
{
QMessageLogContext context;
context.file = nullptr;
outputMessage((QtMsgType)type, context, strInfo);
}
还需要在main. cpp里面注册单例
QmlLog4Qml log4Qml; QQmlApplicationEngine engine; engine.rootContext()->setContextProperty("log4Qml", &log4Qml);
qml里面使用:
可以写上调用filedialog的函数去打开文件