Log Tagging

In addition to creating multiple Logger instances, each with a unique name, which can be used as a runtime tag to filter and search logs using %(logger) in the PatternFormatter format, you can also add static compile-time tags to your log messages. This enhances your ability to search, monitor, categorize, and understand events in your software.

These static tags are included as hashtag-style keywords within your log messages, making it easier to filter and categorize logs based on these predefined tags.

To include tags in your log statements, use the _TAGS macros. You will also need to include the %(tags) placeholder in PatternFormatterOptions for proper display of these tags.

 1#include "quill/Backend.h"
 2#include "quill/Frontend.h"
 3#include "quill/LogMacros.h"
 4#include "quill/Logger.h"
 5#include "quill/Utility.h"
 6#include "quill/sinks/ConsoleSink.h"
 7
 8#include <cstdint>
 9#include <string>
10#include <string_view>
11#include <utility>
12
13#define TAG_1 "foo"
14#define TAG_2 "bar"
15#define TAG_3 "baz"
16
17int main()
18{
19  // Start the backend thread
20  quill::BackendOptions backend_options;
21  quill::Backend::start(backend_options);
22
23  auto console_sink = quill::Frontend::create_or_get_sink<quill::ConsoleSink>("sink_id_1");
24
25  // Ensure the logging pattern includes the %(tags) placeholder to display custom tags.
26  // It is crucial to place %(tags) immediately before the next attribute without any intervening spaces.
27  // This ensures correct formatting when no tags are present, preventing unwanted gaps in the output.
28
29  quill::Logger* logger = quill::Frontend::create_or_get_logger(
30    "root", std::move(console_sink),
31    quill::PatternFormatterOptions{
32      "%(time) [%(thread_id)] %(short_source_location:<28) %(log_level:<9) "
33      "%(tags)%(message)",
34      "%Y-%m-%d %H:%M:%S.%Qms", quill::Timezone::GmtTime});
35
36  LOG_INFO_TAGS(logger, TAGS("random"), "Debug with tags");
37  LOG_INFO_TAGS(logger, TAGS(TAG_2), "Info with tags");
38  LOG_WARNING_TAGS(logger, TAGS(TAG_1, TAG_2), "Warning with tags");
39  LOG_ERROR_TAGS(logger, TAGS(TAG_1, TAG_2, TAG_3), "Info with tags");
40
41  LOG_INFO(logger, "Without tags");
42}

Output:

2024-08-11 01:23:44.463 [46228] tags_logging.cpp:40          INFO      #random Debug with tags
2024-08-11 01:23:44.463 [46228] tags_logging.cpp:41          INFO      #bar Info with tags
2024-08-11 01:23:44.463 [46228] tags_logging.cpp:42          WARNING   #foo #bar Warning with tags
2024-08-11 01:23:44.463 [46228] tags_logging.cpp:43          ERROR     #foo #bar #baz Info with tags
2024-08-11 01:23:44.463 [46228] tags_logging.cpp:45          INFO      Without tags