qBittorrent
filelogger.cpp
Go to the documentation of this file.
1 /*
2  * Bittorrent Client using Qt and libtorrent.
3  * Copyright (C) 2016 sledgehammer999 <hammered999@gmail.com>
4  *
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.
9  *
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.
14  *
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.
18  *
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.
27  */
28 
29 #include "filelogger.h"
30 
31 #include <chrono>
32 
33 #include <QDateTime>
34 #include <QDir>
35 #include <QTextStream>
36 #include <QVector>
37 
38 #include "base/global.h"
39 #include "base/logger.h"
40 #include "base/utils/fs.h"
41 
42 namespace
43 {
44  const std::chrono::seconds FLUSH_INTERVAL {2};
45 }
46 
47 FileLogger::FileLogger(const QString &path, const bool backup, const int maxSize, const bool deleteOld, const int age, const FileLogAgeType ageType)
48  : m_backup(backup)
49  , m_maxSize(maxSize)
50 {
51  m_flusher.setInterval(FLUSH_INTERVAL);
52  m_flusher.setSingleShot(true);
53  connect(&m_flusher, &QTimer::timeout, this, &FileLogger::flushLog);
54 
55  changePath(path);
56  if (deleteOld)
57  this->deleteOld(age, ageType);
58 
59  const Logger *const logger = Logger::instance();
60  for (const Log::Msg &msg : asConst(logger->getMessages()))
61  addLogMessage(msg);
62 
63  connect(logger, &Logger::newLogMessage, this, &FileLogger::addLogMessage);
64 }
65 
67 {
68  closeLogFile();
69 }
70 
71 void FileLogger::changePath(const QString &newPath)
72 {
73  const QDir dir(newPath);
74  dir.mkpath(newPath);
75  const QString tmpPath = dir.absoluteFilePath("qbittorrent.log");
76 
77  if (tmpPath != m_path)
78  {
79  m_path = tmpPath;
80 
81  closeLogFile();
82  m_logFile.setFileName(m_path);
83  openLogFile();
84  }
85 }
86 
87 void FileLogger::deleteOld(const int age, const FileLogAgeType ageType)
88 {
89  const QDateTime date = QDateTime::currentDateTime();
90  const QDir dir(Utils::Fs::branchPath(m_path));
91  const QFileInfoList fileList = dir.entryInfoList(QStringList("qbittorrent.log.bak*")
92  , (QDir::Files | QDir::Writable), (QDir::Time | QDir::Reversed));
93 
94  for (const QFileInfo &file : fileList)
95  {
96  QDateTime modificationDate = file.lastModified();
97  switch (ageType)
98  {
99  case DAYS:
100  modificationDate = modificationDate.addDays(age);
101  break;
102  case MONTHS:
103  modificationDate = modificationDate.addMonths(age);
104  break;
105  default:
106  modificationDate = modificationDate.addYears(age);
107  }
108  if (modificationDate > date)
109  break;
110  Utils::Fs::forceRemove(file.absoluteFilePath());
111  }
112 }
113 
114 void FileLogger::setBackup(const bool value)
115 {
116  m_backup = value;
117 }
118 
120 {
121  m_maxSize = value;
122 }
123 
125 {
126  if (!m_logFile.isOpen()) return;
127 
128  QTextStream stream(&m_logFile);
129 #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
130  stream.setCodec("UTF-8");
131 #endif
132 
133  switch (msg.type)
134  {
135  case Log::INFO:
136  stream << "(I) ";
137  break;
138  case Log::WARNING:
139  stream << "(W) ";
140  break;
141  case Log::CRITICAL:
142  stream << "(C) ";
143  break;
144  default:
145  stream << "(N) ";
146  }
147 
148  stream << QDateTime::fromMSecsSinceEpoch(msg.timestamp).toString(Qt::ISODate) << " - " << msg.message << '\n';
149 
150  if (m_backup && (m_logFile.size() >= m_maxSize))
151  {
152  closeLogFile();
153  int counter = 0;
154  QString backupLogFilename = m_path + ".bak";
155 
156  while (QFile::exists(backupLogFilename))
157  {
158  ++counter;
159  backupLogFilename = m_path + ".bak" + QString::number(counter);
160  }
161 
162  QFile::rename(m_path, backupLogFilename);
163  openLogFile();
164  }
165  else
166  {
167  if (!m_flusher.isActive())
168  m_flusher.start();
169  }
170 }
171 
173 {
174  if (m_logFile.isOpen())
175  m_logFile.flush();
176 }
177 
179 {
180  if (!m_logFile.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)
181  || !m_logFile.setPermissions(QFile::ReadOwner | QFile::WriteOwner))
182  {
183  m_logFile.close();
184  LogMsg(tr("An error occurred while trying to open the log file. Logging to file is disabled."), Log::CRITICAL);
185  }
186 }
187 
189 {
190  m_flusher.stop();
191  m_logFile.close();
192 }
void flushLog()
Definition: filelogger.cpp:172
QTimer m_flusher
Definition: filelogger.h:73
void setBackup(bool value)
Definition: filelogger.cpp:114
QFile m_logFile
Definition: filelogger.h:72
void addLogMessage(const Log::Msg &msg)
Definition: filelogger.cpp:124
FileLogger(const QString &path, bool backup, int maxSize, bool deleteOld, int age, FileLogAgeType ageType)
Definition: filelogger.cpp:47
int m_maxSize
Definition: filelogger.h:71
void changePath(const QString &newPath)
Definition: filelogger.cpp:71
void closeLogFile()
Definition: filelogger.cpp:188
bool m_backup
Definition: filelogger.h:70
void setMaxSize(int value)
Definition: filelogger.cpp:119
QString m_path
Definition: filelogger.h:69
void deleteOld(int age, FileLogAgeType ageType)
Definition: filelogger.cpp:87
void openLogFile()
Definition: filelogger.cpp:178
Definition: logger.h:73
void newLogMessage(const Log::Msg &message)
QVector< Log::Msg > getMessages(int lastKnownId=-1) const
Definition: logger.cpp:93
static Logger * instance()
Definition: logger.cpp:56
constexpr std::add_const_t< T > & asConst(T &t) noexcept
Definition: global.h:42
void LogMsg(const QString &message, const Log::MsgType &type)
Definition: logger.cpp:125
@ WARNING
Definition: logger.h:47
@ CRITICAL
Definition: logger.h:48
@ INFO
Definition: logger.h:46
QString branchPath(const QString &filePath, QString *removed=nullptr)
Definition: fs.cpp:276
bool forceRemove(const QString &filePath)
Definition: fs.cpp:173
const std::chrono::seconds FLUSH_INTERVAL
Definition: filelogger.cpp:44
T value(const QString &key, const T &defaultValue={})
Definition: preferences.cpp:64
file(GLOB QBT_TS_FILES "${qBittorrent_SOURCE_DIR}/src/lang/*.ts") set_source_files_properties($
Definition: CMakeLists.txt:5
QString message
Definition: logger.h:57
MsgType type
Definition: logger.h:55
qint64 timestamp
Definition: logger.h:56