swift
Loading...
Searching...
No Matches
logpattern.cpp
1// SPDX-FileCopyrightText: Copyright (C) 2014 swift Project Community / Contributors
2// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-swift-pilot-client-1
3
4#include "misc/logpattern.h"
5
6#include <algorithm>
7
8#include <QHash>
9#include <QList>
10
11#include "misc/logcategory.h"
13#include "misc/sequence.h"
14
15namespace swift::misc
16{
17 const QHash<QString, CLogPattern> &CLogPattern::allHumanReadablePatterns()
18 {
19 static const QHash<QString, CLogPattern> patterns {
20 { "uncategorized (swift)", exactMatch(CLogCategories::uncategorized()) },
21 { "background task", exactMatch(CLogCategories::worker()) },
22 { "cache", exactMatch(CLogCategories::cache()) },
23 { "cmd.line handling", exactMatch(CLogCategories::cmdLine()) },
24 { "data inconsistency", exactMatch(CLogCategories::dataInconsistency()) },
25 { "DBus", exactMatch(CLogCategories::dbus()) },
26 { "downloading data", exactMatch(CLogCategories::download()) },
27 { "driver", exactMatch(CLogCategories::driver()) },
28 { "flight plan", exactMatch(CLogCategories::flightPlan()) },
29 { "FSD", exactMatch(CLogCategories::fsd()) },
30 { "interpolator", exactMatch(CLogCategories::interpolator()) },
31 { "JSON (conversion)", exactMatch(CLogCategories::json()) },
32 { "model cache", exactMatch(CLogCategories::modelCache()) },
33 { "model GUI", exactMatch(CLogCategories::modelGui()) },
34 { "model loader", exactMatch(CLogCategories::modelLoader()) },
35 { "model mapping", exactMatch(CLogCategories::mapping()) },
36 { "model matching", exactMatch(CLogCategories::matching()) },
37 { "model set cache", exactMatch(CLogCategories::modelSetCache()) },
38 { "network (flight)", exactMatch(CLogCategories::network()) },
39 { "plugin", exactMatch(CLogCategories::plugin()) },
40 { "services", exactMatch(CLogCategories::services()) },
41 { "settings", exactMatch(CLogCategories::settings()) },
42 { "startup phase", exactMatch(CLogCategories::startup()) },
43 { "swift context slots", exactMatch(CLogCategories::contextSlot()) },
44 { "swift contexts", exactMatch(CLogCategories::context()) },
45 { "swift core", exactMatch(CLogCategories::swiftCore()) },
46 { "swift data tool", exactMatch(CLogCategories::swiftDataTool()) },
47 { "swift DB webservice related", exactMatch(CLogCategories::swiftDbWebservice()) },
48 { "swift GUI", exactMatch(CLogCategories::guiComponent()) },
49 { "swift pilot client", exactMatch(CLogCategories::swiftPilotClient()) },
50 { "validation", exactMatch(CLogCategories::validation()) },
51 { "VATSIM specific", exactMatch(CLogCategories::vatsimSpecific()) },
52 { "verification", exactMatch(CLogCategories::verification()) },
53 { "webservice related", exactMatch(CLogCategories::webservice()) },
54 { "wizard", exactMatch(CLogCategories::wizard()) },
55 { "Qt library", startsWith("qt.") },
56 { "uncategorized (default)", exactMatch("default") },
57 { "uncategorized (none)", empty() }
58 };
59 return patterns;
60 }
61
63 {
64 static const QStringList names = allHumanReadablePatterns().keys();
65 return names;
66 }
67
69 {
70 QStringList patternNames;
72 {
74 {
75 patternNames.push_back(name);
76 }
77 }
78 return patternNames;
79 }
80
82 {
83 if (message.getCategories().isEmpty())
84 {
85 return {};
86 }
87 QStringList c(humanReadableNamesFrom(message).join(", "));
88 return c.isEmpty() ? message.getCategories().toQStringList() : c;
89 }
90
92 {
93 static const CLogPattern empty {};
94 auto it = allHumanReadablePatterns().find(name);
95 return it == allHumanReadablePatterns().end() ? empty : *it;
96 }
97
98 CLogPattern::CLogPattern(Strategy strategy, const QSet<QString> &strings) : m_strategy(strategy), m_strings(strings)
99 {
100 static const decltype(m_severities) s { CStatusMessage::SeverityDebug, CStatusMessage::SeverityInfo,
102 m_severities = s;
103 }
104
106
108 {
109 return { ExactMatch, { category.toQString() } };
110 }
111
113 {
114 if (categories.size() == 0)
115 {
116 return empty();
117 }
118 if (categories.size() == 1)
119 {
120 return exactMatch(categories[0]);
121 }
122 const QStringList strList = categories.toQStringList();
123 return { AnyOf, QSet<QString>(strList.begin(), strList.end()) };
124 }
125
127 {
128 if (categories.size() == 0)
129 {
130 return {};
131 }
132 if (categories.size() == 1)
133 {
134 return exactMatch(categories[0]);
135 }
136 const QStringList strList = categories.toQStringList();
137 return { AnyOf, QSet<QString>(strList.begin(), strList.end()) };
138 }
139
140 CLogPattern CLogPattern::startsWith(const QString &prefix) { return { StartsWith, { prefix } }; }
141
142 CLogPattern CLogPattern::endsWith(const QString &suffix) { return { EndsWith, { suffix } }; }
143
144 CLogPattern CLogPattern::contains(const QString &substring) { return { Contains, { substring } }; }
145
146 CLogPattern CLogPattern::empty() { return { Nothing, {} }; }
147
149 {
150 auto result = *this;
151 result.m_severities = { severity };
152 return result;
153 }
154
156 {
157 auto result = *this;
158 result.m_severities = severities;
159 return result;
160 }
161
163 {
164 auto result = *this;
165 result.m_severities.clear();
166 switch (minimumSeverity)
167 {
168 default:
169 case CStatusMessage::SeverityDebug: result.m_severities.insert(CStatusMessage::SeverityDebug); [[fallthrough]];
170 case CStatusMessage::SeverityInfo: result.m_severities.insert(CStatusMessage::SeverityInfo); [[fallthrough]];
172 result.m_severities.insert(CStatusMessage::SeverityWarning);
173 [[fallthrough]];
174 case CStatusMessage::SeverityError: result.m_severities.insert(CStatusMessage::SeverityError);
175 }
176 return result;
177 }
178
179 bool CLogPattern::checkInvariants() const
180 {
181 switch (m_strategy)
182 {
183 case Everything: return m_strings.isEmpty();
184 case ExactMatch: return m_strings.size() == 1;
185 case AnyOf: return m_strings.size() > 1;
186 case AllOf: return m_strings.size() > 1;
187 case StartsWith: return m_strings.size() == 1;
188 case EndsWith: return m_strings.size() == 1;
189 case Contains: return m_strings.size() == 1;
190 case Nothing: return m_strings.isEmpty();
191 default: return false;
192 }
193 }
194
195 bool CLogPattern::match(const CStatusMessage &message) const
196 {
197 if (!checkInvariants())
198 {
199 Q_ASSERT(false);
200 return true;
201 }
202
203 if (!m_severities.contains(message.getSeverity()))
204 {
205 return false;
206 }
207
208 switch (m_strategy)
209 {
210 default:
211 case Everything: return true;
212 case ExactMatch: return message.getCategories().contains(getString());
213 case AnyOf:
214 return std::ranges::any_of(m_strings,
215 [&](const QString &s) { return message.getCategories().contains(s); });
216 case AllOf:
217 return std::ranges::all_of(m_strings,
218 [&](const QString &s) { return message.getCategories().contains(s); });
219 case StartsWith:
220 return message.getCategories().containsBy(
221 [this](const CLogCategory &cat) { return cat.startsWith(getPrefix()); });
222 case EndsWith:
223 return message.getCategories().containsBy(
224 [this](const CLogCategory &cat) { return cat.endsWith(getSuffix()); });
225 case Contains:
226 return message.getCategories().containsBy(
227 [this](const CLogCategory &cat) { return cat.contains(getSubstring()); });
228 case Nothing: return message.getCategories().isEmpty();
229 }
230 }
231
233 {
234 if (!(checkInvariants() && other.checkInvariants()))
235 {
236 Q_ASSERT(false);
237 return false;
238 }
239
240 // For this function to return true, the severities matched by this pattern must be a subset of the severities
241 // matched by the other, and the categories matched by this pattern must be a subset of the categories matched
242 // by the other, and at least one of these two subset relations must be a proper subset relation.
243
244 if (!other.m_severities.contains(m_severities))
245 {
246 // Severities are not a subset
247 return false;
248 }
249 if (m_strategy == other.m_strategy && m_strings == other.m_strings)
250 {
251 // Severities are a subset, and categories are an improper subset, so it all depends
252 // on whether the subset relation of the severities is proper or improper
253 return m_severities.size() < other.m_severities.size();
254 }
255
256 // If we got this far then the severity set is a (proper or improper) subset of the other severity set,
257 // and the question of whether this pattern is a proper subset of the other pattern depends upon whether the
258 // set of categories matched by this pattern is a proper subset of the set of categories matched by the other.
259 // The matrix below is a guide to the implementation that follows.
260 //
261 // Matrix of "categories matched by X is proper subset of categories matched by Y" for two strategies X and Y
262 // 0 means always false
263 // 1 means always true
264 // ? means it depends on a particular relation between their string sets
265 //
266 // Y Ev EM An Al SW EW Co No
267 // X
268 // Ev 0 0 0 0 0 0 0 0 (Everything)
269 // EM 1 0 ? 0 ? ? ? 0 (ExactMatch)
270 // An 1 0 ? 0 ? ? ? 0 (AnyOf)
271 // Al 1 ? ? ? ? ? ? 0 (AllOf)
272 // SW 1 0 0 0 ? 0 ? 0 (StartsWith)
273 // EW 1 0 0 0 0 ? ? 0 (EndsWith)
274 // Co 1 0 0 0 0 0 ? 0 (Contains)
275 // No 1 0 0 0 0 0 0 0 (Nothing)
276
277 if (m_strategy != Everything && other.m_strategy == Everything)
278 {
279 return true;
280 }
281 switch (m_strategy)
282 {
283 case ExactMatch:
284 switch (other.m_strategy)
285 {
286 case AnyOf: return other.m_strings.contains(getString());
287 case StartsWith: return getString().startsWith(other.getPrefix());
288 case EndsWith: return getString().endsWith(other.getSuffix());
289 case Contains: return getString().contains(other.getSubstring());
290 default:;
291 }
292 break;
293 case AnyOf:
294 switch (other.m_strategy)
295 {
296 case AnyOf: return other.m_strings.contains(m_strings) && other.m_strings.size() > m_strings.size();
297 case StartsWith:
298 return std::ranges::all_of(m_strings,
299 [&](const QString &s) { return s.startsWith(other.getPrefix()); });
300 case EndsWith:
301 return std::ranges::all_of(m_strings, [&](const QString &s) { return s.endsWith(other.getSuffix()); });
302 case Contains:
303 return std::ranges::all_of(m_strings,
304 [&](const QString &s) { return s.contains(other.getSubstring()); });
305 default:;
306 }
307 break;
308 case AllOf:
309 switch (other.m_strategy)
310 {
311 case ExactMatch: return m_strings.contains(other.getString());
312 case AnyOf: return !(m_strings & other.m_strings).isEmpty();
313 case AllOf: return m_strings.contains(other.m_strings) && m_strings.size() > other.m_strings.size();
314 case StartsWith:
315 return std::ranges::any_of(m_strings,
316 [&](const QString &s) { return s.startsWith(other.getPrefix()); });
317 case EndsWith:
318 return std::ranges::any_of(m_strings, [&](const QString &s) { return s.endsWith(other.getSuffix()); });
319 case Contains:
320 return std::ranges::any_of(m_strings,
321 [&](const QString &s) { return s.contains(other.getSubstring()); });
322 default:;
323 }
324 break;
325 case StartsWith:
326 switch (other.m_strategy)
327 {
328 case StartsWith:
329 return getPrefix().startsWith(other.getPrefix()) && getPrefix().size() > other.getPrefix().size();
330 case Contains: return getPrefix().contains(other.getSubstring());
331 default:;
332 }
333 break;
334 case EndsWith:
335 switch (other.m_strategy)
336 {
337 case EndsWith:
338 return getSuffix().endsWith(other.getSuffix()) && getSuffix().size() > other.getSuffix().size();
339 case Contains: return getSuffix().contains(other.getSubstring());
340 default:;
341 }
342 break;
343 case Contains:
344 switch (other.m_strategy)
345 {
346 case Contains:
347 return getSubstring().contains(other.getSubstring()) &&
348 getSubstring().size() > other.getSubstring().size();
349 default:;
350 }
351 break;
352 default:;
353 }
354 return false;
355 }
356
358 {
359 Q_UNUSED(i18n)
360 QString strategy;
361 QString categories = m_strings.values().join("|"); // clazy:exclude=container-anti-pattern
362 switch (m_strategy)
363 {
364 case Everything: strategy = "all"; break;
365 case ExactMatch: strategy = "exact match:" + categories; break;
366 case AnyOf: strategy = "any of:" + categories; break;
367 case AllOf: strategy = "all of:" + categories; break;
368 case StartsWith: strategy = "starts with:" + categories; break;
369 case EndsWith: strategy = "ends with:" + categories; break;
370 case Contains: strategy = "contains:" + categories; break;
371 case Nothing: strategy = "none"; break;
372 default: strategy = "<invalid>"; break;
373 }
374 return "{" + CStatusMessage::severitiesToString(m_severities) + "," + strategy + "}";
375 }
376
378 {
379 // a bug in QtDBus prevents us from marshalling m_severities as a list
380 quint8 severities = 0;
381 for (auto s : m_severities)
382 {
383 severities |= (1 << static_cast<int>(s));
384 }
385
386 argument << severities << m_strategy << m_strings.values();
387 }
388
390 {
391 quint8 severities {};
392 QStringList strings;
393 argument >> severities >> m_strategy >> strings;
394 m_strings = QSet<QString>(strings.begin(), strings.end());
395
396 m_severities.clear();
397 for (int s : { 0, 1, 2, 3 })
398 {
399 if (severities & (1 << s))
400 {
401 m_severities.insert(static_cast<CStatusMessage::StatusSeverity>(s));
402 }
403 }
404 }
405
407 {
408 quint8 severities = 0;
409 for (auto s : m_severities)
410 {
411 severities |= (1 << static_cast<int>(s));
412 }
413
414 stream << severities << m_strategy << m_strings.values();
415 }
416
418 {
419 quint8 severities {};
420 QStringList strings;
421 stream >> severities >> m_strategy >> strings;
422 m_strings = QSet<QString>(strings.begin(), strings.end());
423
424 m_severities.clear();
425 for (int s : { 0, 1, 2, 3 })
426 {
427 if (severities & (1 << s))
428 {
429 m_severities.insert(static_cast<CStatusMessage::StatusSeverity>(s));
430 }
431 }
432 }
433} // namespace swift::misc
static const QString & modelGui()
Model UI.
static const QString & swiftDataTool()
swift data tool (aka mapping tool)
static const QString & verification()
Verification.
static const QString & wizard()
Wizard.
static const QString & startup()
Startup of application.
static const QString & driver()
Driver.
static const QString & mapping()
Mapping.
static const QString & contextSlot()
Context slots.
static const QString & services()
Core/base services such as caching etc.
static const QString & modelCache()
Model cache.
static const QString & download()
Generic downloads.
static const QString & swiftDbWebservice()
Webservice with swift DB.
static const QString & vatsimSpecific()
VATSIM specific.
static const QString & context()
Contexts.
static const QString & swiftPilotClient()
swift GUI
static const QString & guiComponent()
GUI components.
static const QString & worker()
Background task.
static const QString & matching()
Matching.
static const QString & flightPlan()
Flight plan.
static const QString & cmdLine()
Cmd.line parsing.
static const QString & fsd()
FSD specific.
static const QString & swiftCore()
swift core
static const QString & cache()
Cache.
static const QString & uncategorized()
Uncategorized.
static const QString & modelLoader()
Model loader.
static const QString & json()
JSON and JSON conversions.
static const QString & dbus()
DBus related.
static const QString & modelSetCache()
Model set cache.
static const QString & webservice()
Webservice.
static const QString & dataInconsistency()
Data inconsistency.
static const QString & settings()
Settings.
static const QString & validation()
Validation.
static const QString & interpolator()
Interpolator.
static const QString & plugin()
Plugin.
static const QString & network()
Network specific, but not necessarily one specific flight network.
A log category is an arbitrary string tag which can be attached to log messages.
Definition logcategory.h:28
bool startsWith(const QString &prefix) const
Returns true if the category string starts with the given prefix.
Definition logcategory.h:40
bool endsWith(const QString &suffix) const
Returns true if the category string ends with the given suffix.
Definition logcategory.h:43
bool contains(const QString &substring) const
Returns true if the category string contains the given substring.
Definition logcategory.h:46
A sequence of log categories.
QStringList toQStringList() const
Convert each of the categories to a QString and return the result as a QStringList.
static QStringList humanReadableNamesFrom(const CStatusMessage &message)
Human readable categories of message.
bool match(const CStatusMessage &message) const
Returns true if the given message matches this pattern.
static QStringList humanOrTechnicalCategoriesFrom(const CStatusMessage &message)
Human or machine readable categories of message.
static const CLogPattern & fromHumanReadableName(const QString &name)
Return a predefined CLogPattern corresponding to the given human-readable name.
QString convertToQString(bool i18n=false) const
Cast as QString.
CLogPattern withSeverities(const QSet< CStatusMessage::StatusSeverity > &severities) const
Returns a CLogPattern which will match the same messages as this one, but only with some given severi...
static CLogPattern endsWith(const QString &suffix)
Returns a CLogPattern which will match any message with a category which ends with the given suffix.
void unmarshallFromDbus(const QDBusArgument &argument)
Unmarshall without begin/endStructure, for when composed within another object.
static CLogPattern allOf(const CLogCategoryList &categories)
Returns a CLogPattern which will match any message with all of the given categories.
static const QStringList & allHumanReadableNames()
Get a list of human-readable names of predefined log patterns.
void marshallToDbus(QDBusArgument &argument) const
Marshall without begin/endStructure, for when composed within another object.
static CLogPattern exactMatch(const CLogCategory &category)
Returns a CLogPattern which will match any message with the given category.
CLogPattern withSeverity(CStatusMessage::StatusSeverity severity) const
Returns a CLogPattern which will match the same messages as this one, but only with a given severity.
static CLogPattern startsWith(const QString &prefix)
Returns a CLogPattern which will match any message with a category which starts with the given prefix...
static CLogPattern contains(const QString &substring)
Returns a CLogPattern which will match any message with a category which contains the given substring...
static CLogPattern empty()
Returns a CLogPattern which will match any message without a category.
void marshalToDataStream(QDataStream &stream) const
Marshal a value to a QDataStream.
bool isProperSubsetOf(const CLogPattern &other) const
Returns true if this pattern is a proper subset of the other pattern.
void unmarshalFromDataStream(QDataStream &stream)
Unmarshal a value from a QDataStream.
static CLogPattern anyOf(const CLogCategoryList &categories)
Returns a CLogPattern which will match any message with any of the given categories.
CLogPattern()
Default constructed CLogPattern will match any message.
CLogPattern withSeverityAtOrAbove(CStatusMessage::StatusSeverity minimumSeverity) const
Returns a CLogPattern which will match the same messages, but only with a severity at or above the gi...
bool containsBy(Predicate p) const
Return true if there is an element for which a given predicate returns true.
Definition range.h:101
bool contains(const T &object) const
Return true if there is an element equal to given object. Uses the most efficient implementation avai...
Definition range.h:109
size_type size() const
Returns number of elements in the sequence.
Definition sequence.h:273
bool isEmpty() const
Synonym for empty.
Definition sequence.h:285
Streamable status message, e.g.
static constexpr auto SeverityInfo
Status severities.
static constexpr auto SeverityError
Status severities.
StatusSeverity getSeverity() const
Message severity.
const CLogCategoryList & getCategories() const
Message categories.
swift::misc::StatusSeverity StatusSeverity
Status severities.
static constexpr auto SeverityDebug
Status severities.
static QString severitiesToString(const QSet< StatusSeverity > &severities)
Severity set as string.
static constexpr auto SeverityWarning
Status severities.
QString toQString(bool i18n=false) const
Cast as QString.
Definition mixinstring.h:74
Free functions in swift::misc.
QList< T >::iterator begin()
QList< T >::iterator end()
bool isEmpty() const const
void push_back(QList< T >::parameter_type value)
void clear()
bool contains(const QSet< T > &other) const const
bool isEmpty() const const
qsizetype size() const const
bool contains(QChar ch, Qt::CaseSensitivity cs) const const
bool endsWith(QChar c, Qt::CaseSensitivity cs) const const
qsizetype size() const const
bool startsWith(QChar c, Qt::CaseSensitivity cs) const const