1// Copyright (C) 2022 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3
4#include "qloggingcategory.h"
5#include "qloggingregistry_p.h"
6
7QT_BEGIN_NAMESPACE
8
9const char qtDefaultCategoryName[] = "default";
10Q_GLOBAL_STATIC(QLoggingCategory, qtDefaultCategory, qtDefaultCategoryName)
11
12/*!
13 \class QLoggingCategory
14 \inmodule QtCore
15 \since 5.2
16 \threadsafe
17
18 \brief The QLoggingCategory class represents a category, or 'area' in the
19 logging infrastructure.
20
21 QLoggingCategory represents a certain logging category - identified by a
22 string - at runtime. A category can be configured to enable or disable
23 logging of messages per message type. An exception are fatal messages,
24 which are always enabled.
25
26 To check whether a message type is enabled or not, use one of these methods:
27 \l isDebugEnabled(), \l isInfoEnabled(), \l isWarningEnabled(), and
28 \l isCriticalEnabled().
29
30 All objects are meant to be configured by a common registry, as described in
31 \l{Configuring Categories}. Different objects can also represent the same
32 category. Therefore, it's \b{not} recommended to export objects across
33 module boundaries, to manipulate the objects directly, or to inherit from
34 QLoggingCategory.
35
36 \section1 Creating Category Objects
37
38 The Q_DECLARE_LOGGING_CATEGORY() and Q_LOGGING_CATEGORY() macros
39 conveniently declare and create QLoggingCategory objects:
40
41 \snippet qloggingcategory/main.cpp 1
42
43 There is also the Q_DECLARE_EXPORTED_LOGGING_CATEGORY() macro in
44 order to use a logging category across library boundaries.
45
46 Category names are free text; to configure categories using \l{Logging Rules}, their
47 names should follow this convention:
48 \list
49 \li Use letters and numbers only.
50 \li Use dots to further structure categories into common areas.
51 \li Avoid the category names: \c{debug}, \c{info}, \c{warning}, and \c{critical}.
52 \li Category names with the \c{qt} prefix are solely reserved for Qt modules.
53 \endlist
54
55 QLoggingCategory objects that are implicitly defined by Q_LOGGING_CATEGORY()
56 are created on first use, in a thread-safe manner.
57
58 \section1 Checking Category Configuration
59
60 QLoggingCategory provides \l isDebugEnabled(), \l isInfoEnabled(),
61 \l isWarningEnabled(), \l isCriticalEnabled(), as well as \l isEnabled()
62 to check whether messages for the given message type should be logged.
63
64 The qCDebug(), qCWarning(), and qCCritical() macros prevent arguments from
65 being evaluated if the respective message types are not enabled for the
66 category, so explicit checking is not needed:
67
68 \snippet qloggingcategory/main.cpp 4
69
70 \section1 Default Category Configuration
71
72 Both the QLoggingCategory constructor and the Q_LOGGING_CATEGORY() macro
73 accept an optional QtMsgType argument, which disables all message types with
74 a lower severity. That is, a category declared with
75
76 \snippet qloggingcategory/main.cpp 5
77
78 logs messages of type \c QtWarningMsg, \c QtCriticalMsg, \c QtFatalMsg, but
79 ignores messages of type \c QtDebugMsg and \c QtInfoMsg.
80
81 If no argument is passed, all messages are logged. Only Qt internal categories
82 which start with \c{qt} are handled differently: For these, only messages of type
83 \c QtInfoMsg, \c QtWarningMsg, \c QtCriticalMsg, and \c QFatalMsg are logged by default.
84
85 \note Logging categories are not affected by your C++ build configuration.
86 That is, whether messages are printed does not change depending on whether
87 the code is compiled with debug symbols ('Debug Build'), optimizations
88 ('Release Build'), or some other combination.
89
90 \section1 Configuring Categories
91
92 You can override the default configuration for categories either by setting
93 logging rules, or by installing a custom filter.
94
95 \section2 Logging Rules
96
97 Logging rules let you enable or disable logging for categories in a flexible
98 way. Rules are specified in text, where every line must have the format:
99
100 \snippet code/src_corelib_io_qloggingcategory.cpp 0
101
102 \c <category> is the name of the category, potentially with \c{*} as a
103 wildcard symbol for the first or last character; or at both positions.
104 The optional \c <type> must be \c debug, \c info, \c warning, or \c critical.
105 Lines that don't fit this scheme are ignored.
106
107 Rules are evaluated in text order, from first to last. That is, if two rules
108 apply to a category/type, the rule that comes later is applied.
109
110 Rules can be set via \l setFilterRules():
111
112 \snippet code/src_corelib_io_qloggingcategory.cpp 1
113
114 Logging rules are automatically loaded from the \c [Rules] section in a logging
115 configuration file. These configuration files are looked up in the QtProject
116 configuration directory, or explicitly set in a \c QT_LOGGING_CONF environment
117 variable:
118
119 \snippet code/src_corelib_io_qloggingcategory.cpp 2
120
121 Logging rules can also be specified in a \c QT_LOGGING_RULES environment variable;
122 multiple rules can also be separated by semicolons:
123
124 \snippet code/src_corelib_io_qloggingcategory.cpp 3
125
126 Rules set by \l setFilterRules() take precedence over rules specified in the
127 QtProject configuration directory. In turn, these rules can be overwritten by those
128 from the configuration file specified by \c QT_LOGGING_CONF, and those set by
129 \c QT_LOGGING_RULES.
130
131 The order of evaluation is as follows:
132 \list 1
133 \li [QLibraryInfo::DataPath]/qtlogging.ini
134 \li QtProject/qtlogging.ini
135 \li \l setFilterRules()
136 \li \c QT_LOGGING_CONF
137 \li \c QT_LOGGING_RULES
138 \endlist
139
140 The \c QtProject/qtlogging.ini file is looked up in all directories returned
141 by QStandardPaths::GenericConfigLocation.
142
143 Set the \c QT_LOGGING_DEBUG environment variable to find out where your logging
144 rules are loaded from.
145
146 \section2 Installing a Custom Filter
147
148 As a lower-level alternative to the text rules, you can also implement a
149 custom filter via \l installFilter(). All filter rules are ignored in this
150 case.
151
152 \section1 Printing the Category
153
154 Use the \c %{category} placeholder to print the category in the default
155 message handler:
156
157 \snippet qloggingcategory/main.cpp 3
158*/
159
160/*!
161 Constructs a QLoggingCategory object with the provided \a category name,
162 and enables all messages with types at least as verbose as \a enableForLevel,
163 which defaults to QtDebugMsg (which enables all categories).
164
165 If \a category is \nullptr, the category name \c "default" is used.
166
167 \note \a category must be kept valid during the lifetime of this object.
168 Using a string literal for it is the usual way to achieve this.
169
170 \since 5.4
171*/
172QLoggingCategory::QLoggingCategory(const char *category, QtMsgType enableForLevel)
173 : d(nullptr),
174 name(nullptr)
175{
176 enabled.storeRelaxed(newValue: 0x01010101); // enabledDebug = enabledWarning = enabledCritical = true;
177
178 if (category)
179 name = category;
180 else
181 name = qtDefaultCategoryName;
182
183 if (QLoggingRegistry *reg = QLoggingRegistry::instance())
184 reg->registerCategory(category: this, enableForLevel);
185}
186
187/*!
188 Destroys a QLoggingCategory object.
189*/
190QLoggingCategory::~QLoggingCategory()
191{
192 if (QLoggingRegistry *reg = QLoggingRegistry::instance())
193 reg->unregisterCategory(category: this);
194}
195
196/*!
197 \fn const char *QLoggingCategory::categoryName() const
198
199 Returns the name of the category.
200*/
201
202/*!
203 \fn bool QLoggingCategory::isDebugEnabled() const
204
205 Returns \c true if debug messages should be shown for this category;
206 \c false otherwise.
207
208 \note The \l qCDebug() macro already does this check before running any
209 code. However, calling this method may be useful to avoid the
210 expensive generation of data for debug output only.
211*/
212
213
214/*!
215 \fn bool QLoggingCategory::isInfoEnabled() const
216
217 Returns \c true if informational messages should be shown for this category;
218 \c false otherwise.
219
220 \note The \l qCInfo() macro already does this check before executing any
221 code. However, calling this method may be useful to avoid the
222 expensive generation of data for debug output only.
223
224 \since 5.5
225*/
226
227
228/*!
229 \fn bool QLoggingCategory::isWarningEnabled() const
230
231 Returns \c true if warning messages should be shown for this category;
232 \c false otherwise.
233
234 \note The \l qCWarning() macro already does this check before executing any
235 code. However, calling this method may be useful to avoid the
236 expensive generation of data for debug output only.
237*/
238
239/*!
240 \fn bool QLoggingCategory::isCriticalEnabled() const
241
242 Returns \c true if critical messages should be shown for this category;
243 \c false otherwise.
244
245 \note The \l qCCritical() macro already does this check before executing any
246 code. However, calling this method may be useful to avoid the
247 expensive generation of data for debug output only.
248*/
249
250/*!
251 Returns \c true if a message of type \a msgtype for the category should be
252 shown; \c false otherwise.
253*/
254bool QLoggingCategory::isEnabled(QtMsgType msgtype) const
255{
256 switch (msgtype) {
257 case QtDebugMsg: return isDebugEnabled();
258 case QtInfoMsg: return isInfoEnabled();
259 case QtWarningMsg: return isWarningEnabled();
260 case QtCriticalMsg: return isCriticalEnabled();
261 case QtFatalMsg: return true;
262 }
263 return false;
264}
265
266/*!
267 Changes the message type \a type for the category to \a enable.
268
269 This method is meant for use only from inside a filter installed with
270 \l installFilter(). For an overview on how to configure categories globally,
271 see \l {Configuring Categories}.
272
273 \note \c QtFatalMsg cannot be changed; it will always remain \c true.
274*/
275void QLoggingCategory::setEnabled(QtMsgType type, bool enable)
276{
277 switch (type) {
278 case QtDebugMsg: bools.enabledDebug.storeRelaxed(newValue: enable); break;
279 case QtInfoMsg: bools.enabledInfo.storeRelaxed(newValue: enable); break;
280 case QtWarningMsg: bools.enabledWarning.storeRelaxed(newValue: enable); break;
281 case QtCriticalMsg: bools.enabledCritical.storeRelaxed(newValue: enable); break;
282 case QtFatalMsg: break;
283 }
284}
285
286/*!
287 \fn QLoggingCategory &QLoggingCategory::operator()()
288
289 Returns the object itself. This allows for both: a QLoggingCategory variable, and
290 a factory method that returns a QLoggingCategory, to be used in \l qCDebug(),
291 \l qCWarning(), \l qCCritical(), or \l qCFatal() macros.
292 */
293
294/*!
295 \fn const QLoggingCategory &QLoggingCategory::operator()() const
296
297 Returns the object itself. This allows for both: a QLoggingCategory variable, and
298 a factory method that returns a QLoggingCategory, to be used in \l qCDebug(),
299 \l qCWarning(), \l qCCritical(), or \l qCFatal() macros.
300 */
301
302/*!
303 Returns a pointer to the global category \c "default" that is used, for
304 example, by qDebug(), qInfo(), qWarning(), qCritical(), or qFatal().
305
306 \note The pointer returned may be null during destruction of static objects.
307 Also, don't \c delete this pointer, as ownership of the category isn't transferred.
308
309 */
310QLoggingCategory *QLoggingCategory::defaultCategory()
311{
312 return qtDefaultCategory();
313}
314
315/*!
316 \typedef QLoggingCategory::CategoryFilter
317
318 This is a typedef for a pointer to a function with the following signature:
319
320 \snippet qloggingcategory/main.cpp 20
321
322 A function with this signature can be installed with \l installFilter().
323*/
324
325/*!
326 \brief Take control of how logging categories are configured.
327
328 Installs a function \a filter that is used to determine which categories and
329 message types should be enabled. If \a filter is \nullptr, the default
330 message filter is reinstated. Returns a pointer to the previously-installed
331 filter.
332
333 Every QLoggingCategory object that already exists is passed to the filter
334 before \c installFilter() returns, and the filter is free to change each
335 category's configuration with \l setEnabled(). Any category it doesn't
336 change will retain the configuration it was given by the prior filter, so
337 the new filter does not need to delegate to the prior filter during this
338 initial pass over existing categories.
339
340 Any new categories added later will be passed to the new filter; a filter
341 that only aims to tweak the configuration of a select few categories, rather
342 than completely overriding the logging policy, can first pass the new
343 category to the prior filter, to give it its standard configuration, and
344 then tweak that as desired, if it is one of the categories of specific
345 interest to the filter. The code that installs the new filter can record the
346 return from \c installFilter() for the filter to use in such later calls.
347
348 When you define your filter, note that it can be called from different threads; but never
349 concurrently. This filter cannot call any static functions from QLoggingCategory.
350
351 Example:
352 \snippet qloggingcategory/main.cpp 21
353
354 installed (in \c{main()}, for example) by
355
356 \snippet qloggingcategory/main.cpp 22
357
358 Alternatively, you can configure the default filter via \l setFilterRules().
359 */
360QLoggingCategory::CategoryFilter
361QLoggingCategory::installFilter(QLoggingCategory::CategoryFilter filter)
362{
363 return QLoggingRegistry::instance()->installFilter(filter);
364}
365
366/*!
367 Configures which categories and message types should be enabled through a
368 set of \a rules.
369
370 Example:
371
372 \snippet qloggingcategory/main.cpp 2
373
374 \note The rules might be ignored if a custom category filter is installed
375 with \l installFilter(), or if the user has defined the \c QT_LOGGING_CONF
376 or the \c QT_LOGGING_RULES environment variable.
377*/
378void QLoggingCategory::setFilterRules(const QString &rules)
379{
380 QLoggingRegistry::instance()->setApiRules(rules);
381}
382
383/*!
384 \macro qCDebug(category)
385 \relates QLoggingCategory
386 \threadsafe
387 \since 5.2
388
389 Returns an output stream for debug messages in the logging category,
390 \a category.
391
392 The macro expands to code that checks whether
393 \l QLoggingCategory::isDebugEnabled() evaluates to \c true.
394 If so, the stream arguments are processed and sent to the message handler.
395
396 Example:
397
398 \snippet qloggingcategory/main.cpp 10
399
400 \note Arguments aren't processed if the debug output for that \a category is not
401 enabled, so don't rely on any side effects.
402
403 \sa qDebug()
404*/
405
406/*!
407 \macro qCDebug(category, const char *message, ...)
408 \relates QLoggingCategory
409 \threadsafe
410 \since 5.3
411
412 Logs a debug message, \a message, in the logging category, \a category.
413 \a message may contain place holders to be replaced by additional arguments,
414 similar to the C printf() function.
415
416 Example:
417
418 \snippet qloggingcategory/main.cpp 13
419
420 \note Arguments aren't processed if the debug output for that \a category is not
421 enabled, so don't rely on any side effects.
422
423 \sa qDebug()
424*/
425
426/*!
427 \macro qCInfo(category)
428 \relates QLoggingCategory
429 \threadsafe
430 \since 5.5
431
432 Returns an output stream for informational messages in the logging category,
433 \a category.
434
435 The macro expands to code that checks whether
436 \l QLoggingCategory::isInfoEnabled() evaluates to \c true.
437 If so, the stream arguments are processed and sent to the message handler.
438
439 Example:
440
441 \snippet qloggingcategory/main.cpp qcinfo_stream
442
443 \note If the debug output for a particular category isn't enabled, arguments
444 won't be processed, so don't rely on any side effects.
445
446 \sa qInfo()
447*/
448
449/*!
450 \macro qCInfo(category, const char *message, ...)
451 \relates QLoggingCategory
452 \threadsafe
453 \since 5.5
454
455 Logs an informational message, \a message, in the logging category, \a category.
456 \a message may contain place holders to be replaced by additional arguments,
457 similar to the C printf() function.
458
459 Example:
460
461 \snippet qloggingcategory/main.cpp qcinfo_printf
462
463 \note If the debug output for a particular category isn't enabled, arguments
464 won't be processed, so don't rely on any side effects.
465
466 \sa qInfo()
467*/
468
469/*!
470 \macro qCWarning(category)
471 \relates QLoggingCategory
472 \threadsafe
473 \since 5.2
474
475 Returns an output stream for warning messages in the logging category,
476 \a category.
477
478 The macro expands to code that checks whether
479 \l QLoggingCategory::isWarningEnabled() evaluates to \c true.
480 If so, the stream arguments are processed and sent to the message handler.
481
482 Example:
483
484 \snippet qloggingcategory/main.cpp 11
485
486 \note If the warning output for a particular category isn't enabled, arguments
487 won't be processed, so don't rely on any side effects.
488
489 \sa qWarning()
490*/
491
492/*!
493 \macro qCWarning(category, const char *message, ...)
494 \relates QLoggingCategory
495 \threadsafe
496 \since 5.3
497
498 Logs a warning message, \a message, in the logging category, \a category.
499 \a message may contain place holders to be replaced by additional arguments,
500 similar to the C printf() function.
501
502 Example:
503
504 \snippet qloggingcategory/main.cpp 14
505
506 \note If the warning output for a particular category isn't enabled, arguments
507 won't be processed, so don't rely on any side effects.
508
509 \sa qWarning()
510*/
511
512/*!
513 \macro qCCritical(category)
514 \relates QLoggingCategory
515 \threadsafe
516 \since 5.2
517
518 Returns an output stream for critical messages in the logging category,
519 \a category.
520
521 The macro expands to code that checks whether
522 \l QLoggingCategory::isCriticalEnabled() evaluates to \c true.
523 If so, the stream arguments are processed and sent to the message handler.
524
525 Example:
526
527 \snippet qloggingcategory/main.cpp 12
528
529
530 \note If the critical output for a particular category isn't enabled, arguments
531 won't be processed, so don't rely on any side effects.
532
533 \sa qCritical()
534*/
535
536/*!
537 \macro qCCritical(category, const char *message, ...)
538 \relates QLoggingCategory
539 \threadsafe
540 \since 5.3
541
542 Logs a critical message, \a message, in the logging category, \a category.
543 \a message may contain place holders to be replaced by additional arguments,
544 similar to the C printf() function.
545
546 Example:
547
548 \snippet qloggingcategory/main.cpp 15
549
550 \note If the critical output for a particular category isn't enabled, arguments
551 won't be processed, so don't rely on any side effects.
552
553 \sa qCritical()
554*/
555
556/*!
557 \macro qCFatal(category)
558 \relates QLoggingCategory
559 \since 6.5
560
561 Returns an output stream for fatal messages in the logging category,
562 \a category.
563
564 If you are using the \b{default message handler}, the returned stream will abort
565 to create a core dump. On Windows, for debug builds, this function will
566 report a \c _CRT_ERROR enabling you to connect a debugger to the application.
567
568 Example:
569
570 \snippet qloggingcategory/main.cpp 16
571
572 \sa qFatal()
573*/
574
575/*!
576 \macro qCFatal(category, const char *message, ...)
577 \relates QLoggingCategory
578 \since 6.5
579
580 Logs a fatal message, \a message, in the logging category, \a category.
581 \a message may contain place holders to be replaced by additional arguments,
582 similar to the C printf() function.
583
584 Example:
585
586 \snippet qloggingcategory/main.cpp 17
587
588 If you are using the \b{default message handler}, this function will abort
589 to create a core dump. On Windows, for debug builds, this function will
590 report a \c _CRT_ERROR enabling you to connect a debugger to the application.
591
592 \sa qFatal()
593*/
594
595/*!
596 \macro Q_DECLARE_LOGGING_CATEGORY(name)
597 \sa Q_LOGGING_CATEGORY(), Q_DECLARE_EXPORTED_LOGGING_CATEGORY()
598 \relates QLoggingCategory
599 \since 5.2
600
601 Declares a logging category \a name. The macro can be used to declare
602 a common logging category shared in different parts of the program.
603
604 This macro must be used outside of a class or method.
605*/
606
607/*!
608 \macro Q_DECLARE_EXPORTED_LOGGING_CATEGORY(name, EXPORT_MACRO)
609 \sa Q_LOGGING_CATEGORY(), Q_DECLARE_LOGGING_CATEGORY()
610 \relates QLoggingCategory
611 \since 6.5
612
613 Declares a logging category \a name. The macro can be used to declare
614 a common logging category shared in different parts of the program.
615
616 This works exactly like Q_DECLARE_LOGGING_CATEGORY(). However,
617 the logging category declared by this macro is additionally
618 qualified with \a EXPORT_MACRO. This is useful if the logging
619 category needs to be exported from a dynamic library.
620
621 For example:
622
623 \code
624 Q_DECLARE_EXPORTED_LOGGING_CATEGORY(lcCore, LIB_EXPORT_MACRO)
625 \endcode
626
627 This macro must be used outside of a class or function.
628*/
629
630/*!
631 \macro Q_LOGGING_CATEGORY(name, string)
632 \sa Q_DECLARE_LOGGING_CATEGORY(), Q_DECLARE_EXPORTED_LOGGING_CATEGORY()
633 \relates QLoggingCategory
634 \since 5.2
635
636 Defines a logging category \a name, and makes it configurable under the
637 \a string identifier. By default, all message types are enabled.
638
639 Only one translation unit in a library or executable can define a category
640 with a specific name. The implicitly-defined QLoggingCategory object is
641 created on first use, in a thread-safe manner.
642
643 This macro must be used outside of a class or method.
644*/
645
646/*!
647 \macro Q_LOGGING_CATEGORY(name, string, msgType)
648 \sa Q_DECLARE_LOGGING_CATEGORY()
649 \relates QLoggingCategory
650 \since 5.4
651
652 Defines a logging category \a name, and makes it configurable under the
653 \a string identifier. By default, messages of QtMsgType \a msgType
654 and more severe are enabled, types with a lower severity are disabled.
655
656 Only one translation unit in a library or executable can define a category
657 with a specific name. The implicitly-defined QLoggingCategory object is
658 created on first use, in a thread-safe manner.
659
660 This macro must be used outside of a class or method.
661*/
662
663QT_END_NAMESPACE
664

source code of qtbase/src/corelib/io/qloggingcategory.cpp