当前位置:网站首页>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 .
边栏推荐
- Selection of PLC
- Transformer self attention mechanism and complete code implementation
- Pytorch learning notes 3 - datasets & dataloaders & transforms
- What are the common English questions in the postgraduate interview?
- 我的注解笔记
- How to calibrate dsx2-8000? Calibration process?
- Briefly introduce EMD decomposition, Hilbert transform and spectral method
- Pytorch learning notes 1 - quick start
- 一、ffmpeg录制音频为pcm文件
- USB network native driver for esxi updated to support esxi7.0 Update 2
猜你喜欢

OpenGL快速配置方法

Vs code basic configuration and beautification

Pycharm2019 set editor theme and default code

Trouble encountered in cable testing -- a case study of a manufacturer?

机器学习笔记 5 —— Logistic Regression

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

clickhouse聚合之探索聚合内部机制

Matlab simulation of radar imaging 1 - LFM signal and its spectrum

Matlab 信号处理

Fluke dtx-1800 and its accessories dtx-cha002 channel adapter channel replacement RJ45 socket notes
随机推荐
Measure computer battery capacity
MySQL安装与使用
微信小程序自定义编译模式
[server usage record] log in to the remote server through the springboard machine and transfer files
EMC experiment practical case ESD electrostatic experiment
Five categories of IP addresses
根据IP地址和子网掩码求主机所在的网络地址和广播地址
Mae mask self encoding is scalable learning
QT custom sliding button (beautiful and easy to use)
T-sne dimension reduction visualization
error: redefinition of ‘xxx‘
测量电脑电池容量
Exploration of Clickhouse aggregation internal mechanism of aggregation
MySQL delete tables without deleting databases
clickhouse建宽表多少列最合适?
Icc2 (III) clock tree synthesis
Efficient Net_ V2
A NOVEL DEEP PARALLEL TIME-SERIES RELATION NETWORK FOR FAULT DIAGNOSIS
qt解析字符串转为json数据并解析
ubunut 服务器上传下载文件