LogIt++
Header-only, macro-first C++ logging library
Loading...
Searching...
No Matches
example_logit_basic.cpp
Go to the documentation of this file.
1
3
4// #define LOGIT_BASE_PATH "E:\\_repoz\\log-it-cpp" <- set via CMake
5
6#include <iostream>
7#include <stdexcept>
8#include <logit.hpp>
9
10namespace {
11
13{
15 LOGIT_TRACE("This is an informational message");
16}
17
18} // namespace
19
20// Example enumeration
21enum class COLORS {
22 NC = -1,
23 BLACK,
24 RED,
25 GREEN,
26 YELLOW,
27 BLUE,
28 MAGENTA,
29 CYAN,
30 WHITE,
31};
32
33std::ostream& operator<<(std::ostream& os, COLORS c) {
34 switch (c) {
35 case COLORS::RED: os << "RED"; break;
36 case COLORS::GREEN: os << "GREEN"; break;
37 case COLORS::BLUE: os << "BLUE"; break;
38 default: os << "UNKNOWN_COLOR"; break;
39 }
40 return os;
41}
42
43namespace logit {
44
45 template<>
46 std::string enum_to_string(COLORS value) {
47 switch (value) {
51 default: return "UNKNOWN_COLOR";
52 };
53 }
54
55};
56
57// Custom error category for demonstration
58class CustomErrorCategory : public std::error_category {
59public:
60 const char* name() const noexcept override {
61 return u8"CustomErrorCategory";
62 }
63
64 std::string message(int ev) const override {
65 switch (ev) {
66 case 1: return u8"Custom error: Invalid operation";
67 case 2: return u8"Custom error: Resource not found";
68 default: return u8"Custom error: Unknown error";
69 }
70 }
71};
72
73// Singleton instance of custom error category
74const std::error_category& custom_error_category() {
75 static CustomErrorCategory instance;
76 return instance;
77}
78
79int main() {
80 std::cout << "Starting logging example..." << std::endl;
81
82 // Add three logging backends: console, default file logger, and unique file logger
88
89 LOGIT_SECTION("App");
90 LOGIT_RAW("Name: sample.desktop.app");
91 LOGIT_RAW("Version: 3.3.106.wzr");
92 LOGIT_SECTION("Proxy");
93 LOGIT_RAW("Proxy enabled: False");
94
96
98
99 bool auth_success = true;
100 std::string email = "user@example.com";
101 LOGIT_TRACE(auth_success, email);
102
103 {
104 LOGIT_SCOPE_INFO("load_config");
105 std::this_thread::sleep_for(std::chrono::milliseconds(1));
106 }
107 {
108 LOGIT_SCOPE_INFO_T(10, "heavy_step");
109 std::this_thread::sleep_for(std::chrono::milliseconds(11));
110 }
111 {
112 int step_id = 7;
113 LOGIT_SCOPE_FMT_INFO("step_{}", step_id);
114 std::this_thread::sleep_for(std::chrono::milliseconds(1));
115 }
116
117 // Demonstrate macros for controlling log frequency and tagging
118 for (int i = 0; i < 5; ++i) {
119 LOGIT_TRACE_ONCE("Trace once example");
120 LOGIT_TRACE_EVERY_N(2, "Trace every 2 iterations", i);
121 LOGIT_TRACE_THROTTLE(100, "Throttled trace", i);
122 LOGIT_TRACE_TAG("Tagged trace", LOGIT_TAG("iteration", i));
123 int id = i * 1000;
124 LOGIT_INFO_TAG("sent order", LOGIT_TAG("order_id", id), LOGIT_TAG("side", "BUY"));
125 std::this_thread::sleep_for(std::chrono::milliseconds(30));
126 }
127
128 // Log various levels of messages
129 float someFloat = 123.456f;
130 int someInt = 789;
131 COLORS color = COLORS::RED;
132
133 LOGIT_INFO(color);
134 LOGIT_FORMAT_INFO("%s", color);
135 LOGIT_INFO("This is an informational message", someFloat, someInt);
136 LOGIT_DEBUG_IF(true, "This debug message is conditionally logged.");
137 LOGIT_WARN("Warning: Something might go wrong here!");
138 LOGIT_PRINT_ERROR("An error has occurred during processing with color: ", color);
139 LOGIT_FATAL("Fatal error! Immediate attention required!");
140
141 // printf-style formatting
142 LOGIT_PRINTF_INFO("%.2f %d", someFloat, someInt);
143
144 // Demonstrating formatted logging for homogeneous variables
145 LOGIT_FORMAT_INFO("%.2f", someFloat, 654.321f); // Two float values
146 LOGIT_FORMAT_INFO("%.4d", someInt, 999); // Two int values
147 LOGIT_FORMAT_INFO("%.2f", 747.000L); // Long double value
148
149 // Stream-based logging
150 LOGIT_STREAM_INFO() << "Stream logging: float=" << someFloat << ", int=" << someInt << ", color=" << color;
151
152 // Writing to the unique file logger using the second logger (index 2)
153 LOGIT_STREAM_TRACE_TO(2) << "Logging to unique file logger with a trace message. Color: " << color;
154 LOGIT_PRINT_INFO("Unique log was written to file: ", LOGIT_GET_LAST_FILE_NAME(2));
155
156 // Wait for all logs to flush
157 LOGIT_WAIT();
158 std::cout << "Default log was written to file: " << LOGIT_GET_LAST_FILE_PATH(1) << std::endl;
159
160 // Logging exceptions
161 try {
162 // Simulate an exception
163 throw std::runtime_error("An example runtime error");
164 } catch (const std::exception& ex) {
165 // Log the exception using the logger
166 LOGIT_FATAL(ex);
167 }
168
169 // Logging std::error_code
170 std::error_code ec(1, custom_error_category());
171 LOGIT_ERROR(ec);
172 LOGIT_FORMAT_ERROR("error_code: (%s, %d)", ec);
173
174# if __cplusplus >= 201703L
175 // Logging std::filesystem::path
176 std::filesystem::path log_path = "/var/log/example.log";
177 LOGIT_INFO(log_path);
178 LOGIT_PRINT_INFO("The log file path is: ", log_path);
179 LOGIT_FORMAT_INFO("%s", log_path);
180# endif
181
182 // Logging std::chrono::duration
183 std::chrono::seconds seconds(120);
184 std::chrono::milliseconds milliseconds(500);
185 std::chrono::microseconds microseconds(123456);
186 std::chrono::minutes minutes(5);
187 std::chrono::hours hours(2);
188
189 LOGIT_PRINT_TRACE("Seconds example: ", seconds);
190 LOGIT_TRACE(milliseconds, minutes, hours);
191 LOGIT_FORMAT_TRACE("%s", microseconds);
192
193 // Logging std::chrono::time_point
194 auto now = std::chrono::system_clock::now();
195 LOGIT_PRINT_INFO("TimePoint example: ", now);
196 LOGIT_INFO(now);
197
198 // Logging void*
199 void* ptr = &now;
200 LOGIT_PRINT_TRACE("Pointer example: ", ptr);
201 LOGIT_INFO(ptr);
202
203 // Logging smart pointers
204 auto shared = std::make_shared<int>(42);
205 LOGIT_PRINT_TRACE("Shared pointer example: ", shared);
206
207# if __cplusplus >= 201402L
208 auto unique = std::make_unique<int>(84);
209# else
210 std::unique_ptr<int> unique(new int(84));
211# endif
212 LOGIT_PRINT_TRACE("Unique pointer example: ", unique);
213
214# if __cplusplus >= 201703L
215 // Logging std::variant
216 std::variant<int, std::string> variant = "Hello, variant!";
217 LOGIT_PRINT_INFO("Variant example: ", variant);
218 variant = 123;
219 LOGIT_TRACE(variant);
220
221 // Logging std::optional
222 std::optional<std::string> optional = "Hello, optional!";
223 LOGIT_PRINT_INFO("Optional example: ", optional);
224 std::optional<std::string> optional_null;
225 LOGIT_ERROR(optional_null);
226# endif
227
228 // Ensure all loggers are flushed and cleaned up before exiting
230
231 std::cout << "Logging example completed." << std::endl;
232 std::this_thread::sleep_for(std::chrono::milliseconds(2000));
233 return 0;
234}
const char * name() const noexcept override
std::string message(int ev) const override
const std::error_category & custom_error_category()
std::ostream & operator<<(std::ostream &os, COLORS c)
int main()
#define LOGIT_ENUM_TO_STR_CASE(value)
Expands to a case statement returning the stringified enum value.
#define LOGIT_RAW(message)
Logs an already formatted raw message without applying logger formatter patterns or level filters.
#define LOGIT_ADD_CONSOLE_DEFAULT()
Macro for adding the default console logger.
#define LOGIT_TRACE0()
#define LOGIT_WAIT()
Macro for waiting for all asynchronous loggers to finish processing.
#define LOGIT_ERROR(...)
#define LOGIT_INFO(...)
#define LOGIT_SHUTDOWN()
Macro for shutting down logger system.
#define LOGIT_WARN(...)
#define LOGIT_FATAL(...)
#define LOGIT_ADD_FILE_LOGGER_DEFAULT()
Macro for adding the default file logger.
#define LOGIT_PRINT_TRACE(...)
#define LOGIT_SET_QUEUE_POLICY(mode)
Sets the behavior when the queue is full.
#define LOGIT_FORMAT_INFO(fmt,...)
#define LOGIT_INFO_TAG(msg,...)
#define LOGIT_SET_MAX_QUEUE(size)
Sets the maximum number of queued tasks.
#define LOGIT_PRINTF_INFO(fmt,...)
#define LOGIT_DEBUG_IF(condition,...)
#define LOGIT_QUEUE_DROP
Backward-compatible alias for dropping the newest task.
#define LOGIT_SECTION(name)
Logs a raw section header in [name] form.
#define LOGIT_FORMAT_ERROR(fmt,...)
#define LOGIT_TRACE_THROTTLE(p,...)
#define LOGIT_FORMAT_TRACE(fmt,...)
#define LOGIT_ADD_UNIQUE_FILE_LOGGER_DEFAULT_SINGLE_MODE()
Macro for adding the default unique file logger in single_mode.
#define LOGIT_SCOPE_INFO_T(threshold_ms, phase)
#define LOGIT_GET_LAST_FILE_NAME(logger_index)
Retrieves last log file name from a specific logger.
#define LOGIT_SCOPE_INFO(phase)
#define LOGIT_STREAM_INFO()
#define LOGIT_SCOPE_FMT_INFO(fmt_str,...)
#define LOGIT_TRACE(...)
#define LOGIT_STREAM_TRACE_TO(index)
#define LOGIT_TAG(k, v)
#define LOGIT_PRINT_INFO(...)
#define LOGIT_GET_LAST_FILE_PATH(logger_index)
Retrieves last log file path from a specific logger.
#define LOGIT_TRACE_ONCE(...)
#define LOGIT_PRINT_ERROR(...)
#define LOGIT_TRACE_TAG(msg,...)
#define LOGIT_TRACE_EVERY_N(n,...)
Unified umbrella header for the LogIt++ library.
The primary namespace for the LogIt++ library.
std::string enum_to_string(EnumType value)
Helper function to convert an enumeration to a string.