1、调用系统调试输出信息:qInstallMessageHandler(Gd::SystemMsg);
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
qInstallMessageHandler(Gd::SystemMsg);
MainWindow w;
w.show();
Gd::sqlHelper.LogAdd(1,"启动软件","",false);
return a.exec();
}
void Gd::SystemMsg(QtMsgType type, const QMessageLogContext &content, const QString &msg)
{
QString LogHead;
switch (type) {
case QtDebugMsg:
LogHead = QString("QtDebugMsg");
break;
case QtInfoMsg:
LogHead = QString("QtInfoMsg");
break;
case QtWarningMsg:
LogHead = QString("QtWarningMsg");
break;
case QtCriticalMsg:
LogHead = QString("QtCriticalMsg");
break;
case QtFatalMsg:
LogHead = QString("QtFatalMsg");
break;
}
QString LogContent=QString("【%1】【%2】【%3】【%4】").arg(content.file).arg(content.line).arg(content.function).arg(msg);
sqlHelper.LogAdd(0,LogHead,LogContent,LogHead=="QtFatalMsg");
}
2、Release模式需要修改.pro文件:DEFINES += QT_MESSAGELOGCONTEXT
qInstallMessageHandler默认在debug模式下输出QMessageLogContext 信息;
- 修改.pro文件后记得清空构建路径文件中的文件,重新qmake一下
#-------------------------------------------------
#
# Project created by QtCreator 2023-02-13T12:00:07
#
#-------------------------------------------------
QT += core gui sql
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets printsupport
TEMPLATE = app
# The following define makes your compiler emit warnings if you use
# any feature of Qt which as been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS\ QT_MESSAGELOGCONTEXT
3、日志存库
- 日志采用批量事务提交:
QSqlDatabase::database().transaction();
QSqlDatabase::database().rollback();
QSqlDatabase::database().commit();
- 系统日志保存时去除单引号'
if(logHead.contains("'")) logHead=logHead.replace("'",""); if(logContent.contains("'")) logContent=logContent.replace("'","");
struct logModel{
QString LogCreateDateTime=(QDateTime::currentDateTime()).toString("yyyy-MM-dd HH:mm:ss");
int LogType;
QString LogHead;
QString LogContent;
};
void SQLiteHelper::LogAdd(int logType,QString logHead,QString logContent,bool isInsert)
{
if(logHead.contains("'"))
logHead=logHead.replace("'","");
if(logContent.contains("'"))
logContent=logContent.replace("'","");
logModel model;
model.LogType=logType;
model.LogHead=logHead;
model.LogContent=logContent;
logsList.append(model);
QString sql;
if(logsList.count()>=100||isInsert)
{
QSqlDatabase::database().transaction();
bool havError=false;
for(int i=0;i<logsList.count();i++)
{
sql=QString(R"(INSERT INTO Log (LogCreateDateTime,LogType,LogHead,LogContent) VALUES ('%1','%2','%3','%4');)").arg(logsList[i].LogCreateDateTime,QString::number(logsList[i].LogType),logsList[i].LogHead,logsList[i].LogContent);
if(!SQLiteHelper::query.exec(sql))
havError=true;
}
if(havError)
QSqlDatabase::database().rollback();
else
{
QSqlDatabase::database().commit();
logsList.clear();
}
}
}