You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

85 lines
2.6 KiB

#include "log_handler.h"
void LogHandler::_log(QtMsgType msgType, const QMessageLogContext &context, const QString &msg) {
// 加锁
static QMutex mutex;
static int count = 0;
QString type;
switch(msgType) {
case QtDebugMsg:
type = QString("Debug");
break;
case QtWarningMsg:
type = QString("Warning");
break;
case QtCriticalMsg:
type = QString("Critical");
break;
case QtFatalMsg:
type = QString("Fatal");
break;
default:
type = QString("Info");
}
mutex.lock();
QString context_info = QString("%1#%2@%3").arg(context.file).arg(context.function).arg(context.line);
QString current_date_time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
QString current_date = QString("(%1)").arg(current_date_time);
QString message = QString("%1|%2|%3: %4").arg(current_date, type, context_info, msg);
_write(message);
mutex.unlock();
count ++;
if(count > 5000){
count = 0;
_clear();
}
}
void LogHandler::init() {
qInstallMessageHandler(_log);
auto logDir = QCoreApplication::applicationDirPath() + LogConfig::getIns()->getFileDir();
QDir dir(logDir);
if (!dir.exists()){
dir.mkdir(logDir);
}
_clear();
}
void LogHandler::_clear() {
auto logCof = LogConfig::getIns();
auto logDir = QCoreApplication::applicationDirPath() + logCof->getFileDir();
QDir dir(logDir);
QFileInfoList fileInfos = dir.entryInfoList(QDir::Files);
auto validity = logCof->getValidity();
foreach (QFileInfo fileInfo, fileInfos) {
if(fileInfo.birthTime().addDays(validity) <= QDateTime::currentDateTime()){
QFile::setPermissions(logDir + "/" +fileInfo.fileName(), QFileDevice::ReadOther | QFileDevice::WriteOther);
QFile::remove(logDir + "/" +fileInfo.fileName());
}
}
}
void LogHandler::_write(const QString& message) {
auto filename = QDateTime::currentDateTime().toString("yyyy-MM-dd");
auto filepath = QCoreApplication::applicationDirPath() + LogConfig::getIns()->getFileDir() + "/" + filename + ".log";
int i = 1;
QFile file(filepath);
while(file.size() >= LogConfig::getIns()->getFileSize()){
auto nextFilename= filename + "_" + i + ".log";
file.setFileName(nextFilename);
i++;
}
if(file.open(QIODevice::WriteOnly | QIODevice::Append)){
QTextStream write(&file);
write.setCodec("utf-8");
write << message << "\r\n";
file.flush();
file.close();
}
}