Debian Codegraph @

src/log/LogManager.cpp

raw
1 // SPDX-FileCopyrightText: 2022 UnionTech Software Technology Co., Ltd.
2 //
3 // SPDX-License-Identifier: LGPL-3.0-or-later
4
5 #include <QtCore>
6 #include "LogManager.h"
7 #include <DSGApplication>
8 #include <Logger.h>
9 #include <ConsoleAppender.h>
10 #include <RollingFileAppender.h>
11 #include <JournalAppender.h>
12
13 #include "dstandardpaths.h"
14 #include "dconfig_org_deepin_dtk_preference.hpp"
15
16 DCORE_BEGIN_NAMESPACE
17
18 #define RULES_KEY ("rules")
19 // Courtesy qstandardpaths_unix.cpp
20 static void appendOrganizationAndApp(QString &path)
21 {
22 #ifndef QT_BOOTSTRAPPED
23 const QString org = QCoreApplication::organizationName();
24 if (!org.isEmpty())
25 path += QLatin1Char('/') + org;
26 const QString appName = QCoreApplication::applicationName();
27 if (!appName.isEmpty())
28 path += QLatin1Char('/') + appName;
29 #else
30 Q_UNUSED(path);
31 #endif
32 }
33
34 #define DEFAULT_FMT "%{time}{yyyy-MM-dd, HH:mm:ss.zzz} [%{type:-7}] [%{file:-20} %{function:-35} %{line}] %{message}"
35
36 class DLogManagerPrivate {
37 public:
38 explicit DLogManagerPrivate(DLogManager *q)
39 : m_format(DEFAULT_FMT)
40 , q_ptr(q)
41 {
42 }
43
44 dconfig_org_deepin_dtk_preference *createDConfig(const QString &appId);
45 void initLoggingRules();
46 void updateLoggingRules();
47
48 QString m_format;
49 QString m_logPath;
50 ConsoleAppender* m_consoleAppender = nullptr;
51 RollingFileAppender* m_rollingFileAppender = nullptr;
52 JournalAppender* m_journalAppender = nullptr;
53 QScopedPointer<dconfig_org_deepin_dtk_preference> m_dsgConfig;
54 QScopedPointer<dconfig_org_deepin_dtk_preference> m_fallbackConfig;
55
56 DLogManager *q_ptr = nullptr;
57 Q_DECLARE_PUBLIC(DLogManager)
58
59 };
60
61 dconfig_org_deepin_dtk_preference *DLogManagerPrivate::createDConfig(const QString &appId)
62 {
63 if (appId.isEmpty())
64 return nullptr;
65
66 auto config = dconfig_org_deepin_dtk_preference::create(appId);
67 QObject::connect(config, &dconfig_org_deepin_dtk_preference::rulesChanged,
68 config, [this](){ updateLoggingRules(); });
69
70 return config;
71 }
72
73 void DLogManagerPrivate::initLoggingRules()
74 {
75 if (qEnvironmentVariableIsSet("DTK_DISABLED_LOGGING_RULES"))
76 return;
77
78 // 1. 未指定 fallbackId 时,以 dsgAppId 为准
79 QString dsgAppId = DSGApplication::id();
80 m_dsgConfig.reset(createDConfig(dsgAppId));
81
82 if (m_dsgConfig) {
83 QObject::connect(m_dsgConfig.data(), &dconfig_org_deepin_dtk_preference::configInitializeSucceed,
84 m_dsgConfig.data(), [this](){ updateLoggingRules(); });
85 QObject::connect(m_dsgConfig.data(), &dconfig_org_deepin_dtk_preference::configInitializeFailed,
86 m_dsgConfig.data(), [this, dsgAppId] {
87 m_dsgConfig.reset();
88 qWarning() << "Logging rules config is invalid, please check `appId` [" << dsgAppId << "]arg is correct";
89 });
90 }
91
92 QString fallbackId = qgetenv("DTK_LOGGING_FALLBACK_APPID");
93 // 2. fallbackId 和 dsgAppId 非空且不等时,都创建和监听变化
94 if (!fallbackId.isEmpty() && fallbackId != dsgAppId)
95 m_fallbackConfig.reset(createDConfig(fallbackId));
96
97 // 3. 默认值和非默认值时,非默认值优先
98 if (m_fallbackConfig) {
99 QObject::connect(m_fallbackConfig.data(), &dconfig_org_deepin_dtk_preference::configInitializeSucceed,
100 m_fallbackConfig.data(), [this](){ updateLoggingRules(); });
101 QObject::connect(m_fallbackConfig.data(), &dconfig_org_deepin_dtk_preference::configInitializeFailed,
102 m_fallbackConfig.data(), [this, fallbackId] {
103 m_fallbackConfig.reset();
104 qWarning() << "Logging rules config is invalid, please check `appId` [" << fallbackId << "]arg is correct";
105 });
106 }
107 }
108
109 void DLogManagerPrivate::updateLoggingRules()
110 {
111 QVariant var;
112 // 4. 优先看 dsgConfig 是否默认值,其次 fallback 是否默认值
113 if (m_dsgConfig && m_dsgConfig->isInitializeSucceed() && !m_dsgConfig->rulesIsDefaultValue()) {
114 var = m_dsgConfig->rules();
115 } else if (m_fallbackConfig && m_dsgConfig->isInitializeSucceed() && !m_fallbackConfig->rulesIsDefaultValue()) {
116 var = m_fallbackConfig->rules();
117 } else if (m_dsgConfig && m_dsgConfig->isInitializeSucceed()) {
118 var = m_dsgConfig->rules();
119 }
120
121 if (var.isValid())
122 QLoggingCategory::setFilterRules(var.toString().replace(";", "\n"));
123 }
124 /*!
125 @~english
126 \class Dtk::Core::DLogManager
127 \inmodule dtkcore
128
129 \brief DLogManager is the deepin user application log manager.
130 */
131
132 DLogManager::DLogManager()
133 :d_ptr(new DLogManagerPrivate(this))
134 {
135 d_ptr->initLoggingRules();
136 }
137
138 void DLogManager::initConsoleAppender(){
139 Q_D(DLogManager);
140 d->m_consoleAppender = new ConsoleAppender;
141 d->m_consoleAppender->setFormat(d->m_format);
142 dlogger->registerAppender(d->m_consoleAppender);
143 }
144
145 void DLogManager::initRollingFileAppender(){
146 Q_D(DLogManager);
147 d->m_rollingFileAppender = new RollingFileAppender(getlogFilePath());
148 d->m_rollingFileAppender->setFormat(d->m_format);
149 d->m_rollingFileAppender->setLogFilesLimit(5);
150 d->m_rollingFileAppender->setDatePattern(RollingFileAppender::DailyRollover);
151 dlogger->registerAppender(d->m_rollingFileAppender);
152 }
153
154 void DLogManager::initJournalAppender()
155 {
156 #if (defined BUILD_WITH_SYSTEMD && defined Q_OS_LINUX)
157 Q_D(DLogManager);
158 d->m_journalAppender = new JournalAppender();
159 dlogger->registerAppender(d->m_journalAppender);
160 #else
161 qWarning() << "BUILD_WITH_SYSTEMD not defined or OS not support!!";
162 #endif
163 }
164
165 /*!
166 @~english
167 \brief Registers the appender to write the log records to the Console.
168
169 \sa registerFileAppender
170 */
171 void DLogManager::registerConsoleAppender(){
172 DLogManager::instance()->initConsoleAppender();
173 }
174
175 /*!
176 @~english
177 \brief Registers the appender to write the log records to the file.
178
179 \sa getlogFilePath
180 \sa registerConsoleAppender
181 */
182 void DLogManager::registerFileAppender() {
183 DLogManager::instance()->initRollingFileAppender();
184 }
185
186 void DLogManager::registerJournalAppender()
187 {
188 DLogManager::instance()->initJournalAppender();
189 }
190
191 /*!
192 @~english
193 \brief Return the path file log storage.
194
195 \brief DLogManager::getlogFilePath Get the log file path
196 \brief The default log path is ~/.cache/<OrganizationName>/<ApplicationName>.log
197 \brief If the environment variable $HOME cannot be acquired, DLogManager will not log anything
198 \sa registerFileAppender
199 */
200 QString DLogManager::getlogFilePath()
201 {
202 //No longer set the default log path (and mkdir) when constructing now, instead set the default value if it's empty when getlogFilePath is called.
203 //Fix the problem that the log file is still created in the default path when the log path is set manually.
204 if (DLogManager::instance()->d_func()->m_logPath.isEmpty()) {
205 if (DStandardPaths::homePath().isEmpty()) {
206 qWarning() << "Unable to locate the cache directory, cannot acquire home directory, and the log will not be written to file..";
207 return QString();
208 }
209
210 QString cachePath(DStandardPaths::path(DStandardPaths::XDG::CacheHome));
211 appendOrganizationAndApp(cachePath);
212
213 if (!QDir(cachePath).exists()) {
214 QDir(cachePath).mkpath(cachePath);
215 }
216 instance()->d_func()->m_logPath = instance()->joinPath(cachePath, QString("%1.log").arg(qApp->applicationName()));
217 }
218
219 return QDir::toNativeSeparators(DLogManager::instance()->d_func()->m_logPath);
220 }
221
222 /*!
223 @~english
224 \brief DLogManager::setlogFilePath Set the log file path
225 \a logFilePath Log file path
226 \brief If the file path set is not the file path, nothing will do, and an output warning
227 */
228 void DLogManager::setlogFilePath(const QString &logFilePath)
229 {
230 QFileInfo info(logFilePath);
231 if (info.exists() && !info.isFile())
232 qWarning() << "invalid file path:" << logFilePath << " is not a file";
233 else
234 DLogManager::instance()->d_func()->m_logPath = logFilePath;
235 }
236
237 void DLogManager::setLogFormat(const QString &format)
238 {
239 //m_format = "%{time}{yyyy-MM-dd, HH:mm:ss.zzz} [%{type:-7}] [%{file:-20} %{function:-35} %{line}] %{message}\n";
240 DLogManager::instance()->d_func()->m_format = format;
241 }
242
243 QString DLogManager::joinPath(const QString &path, const QString &fileName){
244 QString separator(QDir::separator());
245 return QString("%1%2%3").arg(path, separator, fileName);
246 }
247
248 DLogManager::~DLogManager()
249 {
250 }
251
252 DCORE_END_NAMESPACE