Sync translations from Transifex and run lupdate
[qBittorrent.git] / src / app / filelogger.cpp
blob1bdb1d4ad4f993d02e8359589616f6e722922b0c
1 /*
2 * Bittorrent Client using Qt and libtorrent.
3 * Copyright (C) 2016 sledgehammer999 <hammered999@gmail.com>
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * In addition, as a special exception, the copyright holders give permission to
20 * link this program with the OpenSSL project's "OpenSSL" library (or with
21 * modified versions of it that use the same license as the "OpenSSL" library),
22 * and distribute the linked executables. You must obey the GNU General Public
23 * License in all respects for all of the code used other than "OpenSSL". If you
24 * modify file(s), you may extend this exception to your version of the file(s),
25 * but you are not obligated to do so. If you do not wish to do so, delete this
26 * exception statement from your version.
29 #include "filelogger.h"
31 #include <chrono>
33 #include <QDateTime>
34 #include <QDir>
35 #include <QTextStream>
36 #include <QVector>
38 #include "base/global.h"
39 #include "base/logger.h"
40 #include "base/utils/fs.h"
42 namespace
44 const std::chrono::seconds FLUSH_INTERVAL {2};
47 FileLogger::FileLogger(const Path &path, const bool backup
48 , const int maxSize, const bool deleteOld, const int age
49 , const FileLogAgeType ageType)
50 : m_backup(backup)
51 , m_maxSize(maxSize)
53 m_flusher.setInterval(FLUSH_INTERVAL);
54 m_flusher.setSingleShot(true);
55 connect(&m_flusher, &QTimer::timeout, this, &FileLogger::flushLog);
57 changePath(path);
58 if (deleteOld)
59 this->deleteOld(age, ageType);
61 const Logger *const logger = Logger::instance();
62 for (const Log::Msg &msg : asConst(logger->getMessages()))
63 addLogMessage(msg);
65 connect(logger, &Logger::newLogMessage, this, &FileLogger::addLogMessage);
68 FileLogger::~FileLogger()
70 closeLogFile();
73 void FileLogger::changePath(const Path &newPath)
75 // compare paths as strings to perform case sensitive comparison on all the platforms
76 if (newPath.data() == m_path.parentPath().data())
77 return;
79 closeLogFile();
81 m_path = newPath / Path(u"qbittorrent.log"_qs);
82 m_logFile.setFileName(m_path.data());
84 Utils::Fs::mkpath(newPath);
85 openLogFile();
88 void FileLogger::deleteOld(const int age, const FileLogAgeType ageType)
90 const QDateTime date = QDateTime::currentDateTime();
91 const QDir dir {m_path.parentPath().data()};
92 const QFileInfoList fileList = dir.entryInfoList(QStringList(u"qbittorrent.log.bak*"_qs)
93 , (QDir::Files | QDir::Writable), (QDir::Time | QDir::Reversed));
95 for (const QFileInfo &file : fileList)
97 QDateTime modificationDate = file.lastModified();
98 switch (ageType)
100 case DAYS:
101 modificationDate = modificationDate.addDays(age);
102 break;
103 case MONTHS:
104 modificationDate = modificationDate.addMonths(age);
105 break;
106 default:
107 modificationDate = modificationDate.addYears(age);
109 if (modificationDate > date)
110 break;
111 Utils::Fs::removeFile(Path(file.absoluteFilePath()));
115 void FileLogger::setBackup(const bool value)
117 m_backup = value;
120 void FileLogger::setMaxSize(const int value)
122 m_maxSize = value;
125 void FileLogger::addLogMessage(const Log::Msg &msg)
127 if (!m_logFile.isOpen()) return;
129 QTextStream stream(&m_logFile);
130 #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
131 stream.setCodec("UTF-8");
132 #endif
134 switch (msg.type)
136 case Log::INFO:
137 stream << QStringView(u"(I) ");
138 break;
139 case Log::WARNING:
140 stream << QStringView(u"(W) ");
141 break;
142 case Log::CRITICAL:
143 stream << QStringView(u"(C) ");
144 break;
145 default:
146 stream << QStringView(u"(N) ");
149 stream << QDateTime::fromSecsSinceEpoch(msg.timestamp).toString(Qt::ISODate) << QStringView(u" - ") << msg.message << QChar(u'\n');
151 if (m_backup && (m_logFile.size() >= m_maxSize))
153 closeLogFile();
154 int counter = 0;
155 Path backupLogFilename = m_path + u".bak";
157 while (backupLogFilename.exists())
159 ++counter;
160 backupLogFilename = m_path + u".bak" + QString::number(counter);
163 Utils::Fs::renameFile(m_path, backupLogFilename);
164 openLogFile();
166 else
168 if (!m_flusher.isActive())
169 m_flusher.start();
173 void FileLogger::flushLog()
175 if (m_logFile.isOpen())
176 m_logFile.flush();
179 void FileLogger::openLogFile()
181 if (!m_logFile.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)
182 || !m_logFile.setPermissions(QFile::ReadOwner | QFile::WriteOwner))
184 m_logFile.close();
185 LogMsg(tr("An error occurred while trying to open the log file. Logging to file is disabled."), Log::CRITICAL);
189 void FileLogger::closeLogFile()
191 m_flusher.stop();
192 m_logFile.close();