当前位置:网站首页>QT implementation outputs relevant information to log file
QT implementation outputs relevant information to log file
2022-07-28 06:32:00 【Schoolmate Xiaotu!】
Preface
In the development work , When the program is in use , An error occurred , For users , View log information , It is necessary to check the problem preliminarily
Be careful : I am here windows Writing of environment ,linux The path and command of are somewhat different ,linux Students of the environment cannot directly copy
6.15 to update :
You can also see on the Internet by calling qInstallMessageHandler Install message handler , This is the introduction of the message handler in the official document , That is, we can customize qDebug,qInfo When printing what information , Where to print the information . Put the code at the end of the text

Go straight to the code :
.h file
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
QT_BEGIN_NAMESPACE
namespace Ui {
class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
static int WriteLog(QString errInfo);
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
.cpp file
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QCoreApplication>
#include <QDir>
#include <QProcess>
#include <QDebug>
#include <QDateTime>
#include <QFile>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
WriteLog("---success--- The live broadcast function is set successfully ");
WriteLog("----infos---- Inserting information into the database ......");
WriteLog("---warning--- No mount information ");
WriteLog("----error----/etc/lancoo/rec-server.ini file does not exist ");
}
MainWindow::~MainWindow()
{
delete ui;
}
// Main code
int MainWindow::WriteLog(QString info)
{
QString localApplicationDirPath = QCoreApplication::applicationDirPath(); // The directory where the executable program is located
QString log_file;
QString log_dir=localApplicationDirPath+"/log";
QDir dir(log_dir);
//cmd You need to use \, Use / Report errors
log_dir.replace("/","\\");
if(!dir.exists())
{
// Create in the directory where the executable program is located log file
system(QString(" mkdir %1").arg(log_dir).toStdString().data());
qDebug()<<log_dir;
}
QDateTime current_date_time =QDateTime::currentDateTime();
QString date = current_date_time.toString("yyyy-MM-dd");
// stay c++ in \ To signify an escape ,\\ Is a character \
log_file=log_dir+"\\"+"log_"+date+".txt";
// Save the contents of the original file , direct write It will cover up the original content
QFile file_read(log_file);
file_read.open(QIODevice::ReadOnly);
QByteArray file_readAll = file_read.readAll();
file_read.close();
// Write information to the file
QFile file_write(log_file);
if(file_write.open(QIODevice::WriteOnly)){
file_write.write(file_readAll.data());
QString temp_info;
temp_info+="[";
temp_info+=current_date_time.toString("yyyy-MM-dd hh:mm:ss");
temp_info+="] ";
temp_info+=info;
temp_info+="\r\n"; // A newline ,linux by \n
file_write.write(temp_info.toStdString().data());
}
file_write.close();
return
}
Just look at the main code , It is defined as a static method so that it can be easily called in other classes
log The file is in the directory where the executable program is located
Be careful :qt Manage compiled files and source files separately , Through shadow construction , Executable files are probably in other directories . If you check here , Then go to the corresponding directory to find the executable program , If this is not checked , Choose the code source file directory to find



In the custom writeLog On the basis of, we customize the message handler :
Will customize the function myMessageOutput Written in main.cpp in , The installation of message handlers is written in main() In the method , In this way, all classes in the global qDebug Can print the information directly to the log file . Comment out qInstallMessageHandler(myMessageOutput); perhaps qInstallMessageHandler(0) To reply to the message handler
#include "mainwindow.h"
#include <QApplication>
#include <QDateTime>
#include <QDir>
#include <QFile>
#include <QMutex>
#include <QTextStream>
#include <QDebug>
void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
// Lock
static QMutex mutex;
mutex.lock();
QByteArray localMsg = msg.toLocal8Bit();
QString strMsg("");
switch(type)
{
case QtDebugMsg:
strMsg = QString("----Debug----");
break;
case QtInfoMsg:
strMsg = QString("----Infos----");
break;
case QtWarningMsg:
strMsg = QString("---Warning---");
break;
case QtCriticalMsg:
strMsg = QString("---Critical---");
break;
case QtFatalMsg:
strMsg = QString("----Fatal----");
break;
}
// Format output information
QString strDateTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
QString strMessage = QString("[%1] %5 %6\t-------------File:%2 Line:%3 Function:%4 ")
.arg(strDateTime).arg(context.file).arg(context.line).arg(context.function).arg(strMsg).arg(localMsg.constData());
// Get the directory where the executable program is located
QString localApplicationDirPath = QCoreApplication::applicationDirPath();
QString log_file;
QString log_dir=localApplicationDirPath+"/log";
QDir dir(log_dir);
//cmd You need to use \, Use / Report errors
log_dir.replace("/","\\");
if(!dir.exists())
{
// Create in the directory where the executable program is located log file
system(QString(" mkdir %1").arg(log_dir).toStdString().data());
}
QDateTime current_date_time =QDateTime::currentDateTime();
QString date = current_date_time.toString("yyyy-MM-dd");
// stay c++ in \ To signify an escape ,\\ Is a character "\"
log_file=log_dir+"\\"+"log_"+date+".txt";
// Output information to file ( Reading and writing 、 Additional form )
QFile file(log_file);
file.open(QIODevice::ReadWrite | QIODevice::Append);
QTextStream stream(&file);
stream << strMessage << "\r\n";
file.flush();
file.close();
// Unlock
mutex.unlock();
}
int main(int argc, char *argv[])
{
// Install message handler
qInstallMessageHandler(myMessageOutput);
QApplication a(argc, argv);
MainWindow w;
qDebug("This is a debug message.");
qInfo("This is a info message.");
qWarning("This is a warning message.");
qCritical("This is a critical message.");
w.show();
return a.exec();
}
In this way, you can check the error information directly through the log file in the distribution program
Running results :

It's not easy to code words , If this blog is helpful to you , Please praise the collection , Thank you very much ! There is something wrong , Can comment on the area of communication .
边栏推荐
- Matlab simulation of radar imaging 3 - multi-target detection
- 雷达成像 Matlab 仿真 1 —— LFM信号及其频谱
- Hugging face 的入门使用
- Detailed explanation of word mail merge function: after merging, multiple word documents are generated and blank pages are deleted
- Briefly introduce EMD decomposition, Hilbert transform and spectral method
- 【学习笔记】驱动
- How to test industrial Ethernet cables (using fluke dsx-8000)?
- 量化交易机器人系统开发
- 【学习笔记】编码能力
- 自定义组件--样式
猜你喜欢

qt批量操作控件,并设置信号槽

How to calibrate dsx2-8000? Calibration process?

clickhouse建宽表多少列最合适?

详解安装msdn 2015及其注意事项

自定义组件--插槽

Word邮件合并功能详解:合并后生成多个word文档,删除空白页

Pytorch learning note 4 - automatic calculation of gradient descent autograd

How to test industrial Ethernet cables (using fluke dsx-8000)?

MySQL join skills

IMS-FACNN(Improved Multi-Scale Convolution Neural Network integrated with a Feature Attention Mecha
随机推荐
使用wampserver3.2.6时切换中文时造成启动失败
根据IP地址和子网掩码求主机所在的网络地址和广播地址
clickhouse聚合之探索聚合内部机制
【服务器使用记录】通过跳板机登录远程服务器并进行文件传输
MySQL join skills
Pyppeteer 被识别 绕过检测
Synopsys Multivoltage Flow
Vs code basic configuration and beautification
EfficientNET_ V1
自定义组件--数据监听器
What are the common English questions in the postgraduate interview?
Listener
A NOVEL DEEP PARALLEL TIME-SERIES RELATION NETWORK FOR FAULT DIAGNOSIS
Weight decay
VI and VIM commands
【学习笔记】线程创建
npm yarn相关的操作
NPM yarn related operations
保研面试中常见的英语问题有哪些?
qt自定义滑动按钮(美观且使用方便)