131 lines
2.7 KiB
C++
131 lines
2.7 KiB
C++
#include "core/Logger.h"
|
|
#include <QDateTime>
|
|
#include <QFileInfo>
|
|
#include <QDir>
|
|
|
|
Logger* Logger::s_instance = nullptr;
|
|
|
|
Logger* Logger::instance()
|
|
{
|
|
if (!s_instance) {
|
|
s_instance = new Logger();
|
|
}
|
|
return s_instance;
|
|
}
|
|
|
|
Logger::Logger(QObject *parent)
|
|
: QObject(parent)
|
|
, m_maxLines(100000) // 保留最新10000行
|
|
, m_currentLines(0)
|
|
{
|
|
}
|
|
|
|
Logger::~Logger()
|
|
{
|
|
}
|
|
|
|
void Logger::setLogFile(const QString &filePath)
|
|
{
|
|
QMutexLocker locker(&m_mutex);
|
|
m_logFilePath = filePath;
|
|
|
|
// Count existing lines
|
|
QFile file(m_logFilePath);
|
|
if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
|
|
m_currentLines = 0;
|
|
while (!file.atEnd()) {
|
|
file.readLine();
|
|
m_currentLines++;
|
|
}
|
|
file.close();
|
|
}
|
|
}
|
|
|
|
void Logger::setMaxLines(int maxLines)
|
|
{
|
|
QMutexLocker locker(&m_mutex);
|
|
m_maxLines = maxLines;
|
|
}
|
|
|
|
void Logger::log(const QString &message)
|
|
{
|
|
writeLog("LOG", message);
|
|
}
|
|
|
|
void Logger::debug(const QString &message)
|
|
{
|
|
writeLog("DEBUG", message);
|
|
}
|
|
|
|
void Logger::info(const QString &message)
|
|
{
|
|
writeLog("INFO", message);
|
|
}
|
|
|
|
void Logger::warning(const QString &message)
|
|
{
|
|
writeLog("WARN", message);
|
|
}
|
|
|
|
void Logger::error(const QString &message)
|
|
{
|
|
writeLog("ERROR", message);
|
|
}
|
|
|
|
void Logger::writeLog(const QString &level, const QString &message)
|
|
{
|
|
QMutexLocker locker(&m_mutex);
|
|
|
|
if (m_logFilePath.isEmpty()) {
|
|
return;
|
|
}
|
|
|
|
QString timestamp = QDateTime::currentDateTime().toString("[yyyy-MM-dd hh:mm:ss.zzz]");
|
|
QString logLine = QString("%1 [%2] %3\n").arg(timestamp).arg(level).arg(message);
|
|
|
|
QFile file(m_logFilePath);
|
|
if (file.open(QIODevice::Append | QIODevice::Text)) {
|
|
QTextStream out(&file);
|
|
out << logLine;
|
|
file.close();
|
|
|
|
m_currentLines++;
|
|
|
|
// Check if we need to trim the log
|
|
if (m_currentLines > m_maxLines) {
|
|
checkAndTrimLog();
|
|
}
|
|
}
|
|
}
|
|
|
|
void Logger::checkAndTrimLog()
|
|
{
|
|
// Read all lines
|
|
QFile file(m_logFilePath);
|
|
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
|
|
return;
|
|
}
|
|
|
|
QStringList lines;
|
|
QTextStream in(&file);
|
|
while (!in.atEnd()) {
|
|
lines.append(in.readLine());
|
|
}
|
|
file.close();
|
|
|
|
// Keep only the last m_maxLines
|
|
if (lines.size() > m_maxLines) {
|
|
lines = lines.mid(lines.size() - m_maxLines);
|
|
}
|
|
|
|
// Write back
|
|
if (file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) {
|
|
QTextStream out(&file);
|
|
for (const QString &line : lines) {
|
|
out << line << "\n";
|
|
}
|
|
file.close();
|
|
m_currentLines = lines.size();
|
|
}
|
|
}
|