main函数中加入:
qInstallMessageHandler(CLog::OutputMessage);
1.头文件
#ifndef CLOG_H
#define CLOG_H
#include <QObject>
#include <QMutex>
class CLog : public QObject
{
Q_OBJECT
public:
CLog(QObject* parent = nullptr);
static void OutputMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg); // 输出日志
static bool DeleteLogFile(); // 删除日志文件
private:
static QMutex m_mutex;
};
#endif // CLOG_H
2.源文件
#include "clog.h"
#include <QFile>
#include <QCoreApplication>
#include <QDateTime>
#include <QTextStream>
#include <QDir>
const int day_max = 300;
QMutex CLog::m_mutex;
void CLog::OutputMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
QMutexLocker lock(&m_mutex);
QString current_date_time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
QString text = QString("[%1]%2").arg(current_date_time).arg(msg);
QString path = QCoreApplication::applicationDirPath() + "/log/";
QDir dir(path);
if(!dir.exists()) {
dir.mkpath(path);
}
QFile file(path + "log.txt");
if(!file.open(QIODevice::WriteOnly | QIODevice::Append)) {
return;
}
QTextStream stream(&file);
stream << text << endl;
file.flush();
file.close();
}
bool CLog::DeleteLogFile()
{
QString path = QCoreApplication::applicationDirPath() + "/log/log.txt";
QFile file(path);
if(!file.open(QIODevice::ReadOnly)) {
return false;
}
char buff[64];
memset(buff, 0, 64);
file.readLine(buff, 64);
file.close();
QString data = QString(buff);
int pos = data.indexOf("]");
if(pos == -1 || pos < 4) {
return false;
}
data = data.mid(1, pos - 1);
QDateTime start = QDateTime::fromString(data, "yyyy-MM-dd hh:mm:ss");
QDateTime currentTime = QDateTime::currentDateTime();
auto days = start.daysTo(currentTime);
if(days > day_max) {
QFile::remove(path);
}
return true;
}
CLog::CLog(QObject* parent) :QObject(parent)
{
}