WebAPI: Add `forced` parameter to `torrents/add`
[qBittorrent.git] / src / app / filelogger.cpp
blob5436c13926a336e8b3082c884fbc29a7a07a76db
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 <QList>
36 #include <QTextStream>
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"_s);
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*"_s)
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);
131 switch (msg.type)
133 case Log::INFO:
134 stream << QStringView(u"(I) ");
135 break;
136 case Log::WARNING:
137 stream << QStringView(u"(W) ");
138 break;
139 case Log::CRITICAL:
140 stream << QStringView(u"(C) ");
141 break;
142 default:
143 stream << QStringView(u"(N) ");
146 stream << QDateTime::fromSecsSinceEpoch(msg.timestamp).toString(Qt::ISODate) << QStringView(u" - ") << msg.message << QChar(u'\n');
148 if (m_backup && (m_logFile.size() >= m_maxSize))
150 closeLogFile();
151 int counter = 0;
152 Path backupLogFilename = m_path + u".bak";
154 while (backupLogFilename.exists())
156 ++counter;
157 backupLogFilename = m_path + u".bak" + QString::number(counter);
160 Utils::Fs::renameFile(m_path, backupLogFilename);
161 openLogFile();
163 else
165 if (!m_flusher.isActive())
166 m_flusher.start();
170 void FileLogger::flushLog()
172 if (m_logFile.isOpen())
173 m_logFile.flush();
176 void FileLogger::openLogFile()
178 if (!m_logFile.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)
179 || !m_logFile.setPermissions(QFile::ReadOwner | QFile::WriteOwner))
181 m_logFile.close();
182 LogMsg(tr("An error occurred while trying to open the log file. Logging to file is disabled."), Log::CRITICAL);
186 void FileLogger::closeLogFile()
188 m_flusher.stop();
189 m_logFile.close();