Logger System 0.1.3
High-performance C++20 thread-safe logging system with asynchronous capabilities
Loading...
Searching...
No Matches
critical_logging_example.cpp
Go to the documentation of this file.
1// BSD 3-Clause License
2// Copyright (c) 2021-2025, 🍀☀🌕🌥 🌊
3// See the LICENSE file in the project root for full license information.
4
22#include <kcenon/common/interfaces/logger_interface.h>
23#include <iostream>
24
25using namespace kcenon::logger;
26namespace ci = kcenon::common::interfaces;
32 std::cout << "\n=== Example 1: Basic Critical Writer ===\n";
33
34 // Create logger with critical writer
35 logger log(false); // Synchronous mode for this example
36
37 // Wrap file writer with critical_writer
38 auto file = std::make_unique<file_writer>("logs/critical_basic.log");
39 auto critical = std::make_unique<critical_writer>(
40 std::move(file),
42 .force_flush_on_critical = true,
43 .force_flush_on_error = false,
44 .write_ahead_log = false,
45 .sync_on_critical = true
46 }
47 );
48
49 log.add_writer(std::move(critical));
50
51 // Normal logs (buffered)
52 log.log(ci::log_level::info, std::string("Application started"));
53 log.log(ci::log_level::debug, std::string("Debug information"));
54
55 // Critical log (immediately flushed to disk)
56 log.log(ci::log_level::critical, std::string("Critical error occurred - guaranteed on disk"));
57
58 // Even if the program crashes here, the critical log above is safe
59 std::cout << "Critical log written and flushed immediately\n";
60}
61
67 std::cout << "\n=== Example 2: Write-Ahead Logging ===\n";
68
69 logger log(false);
70
71 auto file = std::make_unique<rotating_file_writer>(
72 "logs/wal_main.log",
73 1024 * 1024, // 1 MB per file
74 5 // Keep 5 rotations
75 );
76
77 auto critical = std::make_unique<critical_writer>(
78 std::move(file),
80 .force_flush_on_critical = true,
81 .write_ahead_log = true, // Enable WAL
82 .wal_path = "logs/.critical.wal",
83 .sync_on_critical = true
84 }
85 );
86
87 log.add_writer(std::move(critical));
88
89 log.log(ci::log_level::info, std::string("Normal log"));
90 log.log(ci::log_level::critical, std::string("Critical log - written to WAL first"));
91
92 std::cout << "Check logs/.critical.wal for write-ahead log entries\n";
93}
94
100 std::cout << "\n=== Example 3: Hybrid Writer (Async + Critical) ===\n";
101
102 logger log(false);
103
104 // Hybrid writer combines:
105 // - Async queue for normal/debug/info/warn (high performance)
106 // - Immediate flush for error/critical/fatal (no loss)
107 auto hybrid = std::make_unique<hybrid_writer>(
108 std::make_unique<file_writer>("logs/hybrid.log"),
110 .force_flush_on_critical = true,
111 .force_flush_on_error = true // Also flush errors immediately
112 },
113 10000 // Async queue size
114 );
115
116 log.add_writer(std::move(hybrid));
117
118 // These go through async queue (fast)
119 for (int i = 0; i < 100; ++i) {
120 log.log(ci::log_level::info, "High-frequency log " + std::to_string(i));
121 }
122
123 // This bypasses the queue and flushes immediately (safe)
124 log.log(ci::log_level::critical, std::string("Critical error - no loss guaranteed"));
125
126 std::cout << "Hybrid writer provides both performance and safety\n";
127}
128
134 std::cout << "\n=== Example 4: Production Configuration ===\n";
135
136 // Use logger_builder for comprehensive configuration
137 auto result = logger_builder()
138 .with_async(true) // Async for performance
139 .with_buffer_size(32768) // Large buffer for high throughput
140 .with_min_level(log_level::info) // Production: info and above
141 .add_writer("main",
142 std::make_unique<hybrid_writer>(
143 std::make_unique<rotating_file_writer>(
144 "logs/production.log",
145 100 * 1024 * 1024, // 100 MB per file
146 10 // Keep 10 rotations
147 ),
149 .force_flush_on_critical = true,
150 .force_flush_on_error = true,
151 .write_ahead_log = true,
152 .wal_path = "logs/.production.wal",
153 .sync_on_critical = true,
154 .critical_write_timeout_ms = 5000
155 },
156 50000 // Large async queue
157 )
158 )
159 .build();
160
161 if (!result) {
162 std::cerr << "Failed to build logger: " << result.error_message() << "\n";
163 return;
164 }
165
166 auto log = std::move(result.value());
167 log->start();
168
169 // Production logging examples
170 log->log(ci::log_level::info, std::string("Service started"));
171 log->log(ci::log_level::warning, std::string("Cache miss rate high"));
172 log->log(ci::log_level::error, std::string("Database connection timeout"));
173 log->log(ci::log_level::critical, std::string("Out of memory - terminating"));
174
175 log->flush();
176 log->stop();
177
178 std::cout << "Production setup complete\n";
179 std::cout << "Configuration:\n";
180 std::cout << " - Async logging for normal messages (performance)\n";
181 std::cout << " - Immediate flush for errors and critical (safety)\n";
182 std::cout << " - Write-ahead logging for crash recovery\n";
183 std::cout << " - File rotation to manage disk space\n";
184}
185
190 std::cout << "\n=== Example 5: Error Handling & Statistics ===\n";
191
192 logger log(false);
193
194 auto critical = std::make_unique<critical_writer>(
195 std::make_unique<file_writer>("logs/stats.log"),
197 .force_flush_on_critical = true,
198 .write_ahead_log = true,
199 .wal_path = "logs/.stats.wal"
200 }
201 );
202
203 // Store reference before moving
204 const auto& config = critical->get_config();
205 const auto& stats = critical->get_stats();
206
207 log.add_writer(std::move(critical));
208
209 // Generate logs
210 log.log(ci::log_level::info, std::string("Info message"));
211 log.log(ci::log_level::warning, std::string("Warning message"));
212 log.log(ci::log_level::error, std::string("Error message"));
213 log.log(ci::log_level::critical, std::string("Critical message 1"));
214 log.log(ci::log_level::critical, std::string("Critical message 2"));
215 log.log(ci::log_level::critical, std::string("Fatal message"));
216
217 // Check statistics
218 std::cout << "\nConfiguration:\n";
219 std::cout << " Force flush on critical: " << config.force_flush_on_critical << "\n";
220 std::cout << " Force flush on error: " << config.force_flush_on_error << "\n";
221 std::cout << " WAL enabled: " << config.write_ahead_log << "\n";
222 std::cout << " Sync on critical: " << config.sync_on_critical << "\n";
223
224 std::cout << "\nStatistics:\n";
225 std::cout << " Total critical writes: " << stats.total_critical_writes.load() << "\n";
226 std::cout << " Total flushes: " << stats.total_flushes.load() << "\n";
227 std::cout << " WAL writes: " << stats.wal_writes.load() << "\n";
228 std::cout << " Sync calls: " << stats.sync_calls.load() << "\n";
229
230 // Runtime configuration change
231 std::cout << "\nChanging configuration at runtime...\n";
232 // Note: set_force_flush_on_critical() would be called on the writer directly
233 // This example shows the concept
234}
235
236int main() {
237 std::cout << "Critical Logging Examples\n";
238 std::cout << "=========================\n";
239
240 try {
246
247 std::cout << "\n=== All Examples Completed Successfully ===\n";
248 std::cout << "\nCheck the logs/ directory for output files:\n";
249 std::cout << " - *.log: Main log files\n";
250 std::cout << " - .*.wal: Write-ahead log files\n";
251
252 } catch (const std::exception& e) {
253 std::cerr << "Error: " << e.what() << "\n";
254 return 1;
255 }
256
257 return 0;
258}
Asynchronous wrapper for log writers.
Builder pattern for logger construction with validation.
logger_builder & with_min_level(log_level level)
logger_builder & with_async(bool async=true)
logger_builder & add_writer(const std::string &name, log_writer_ptr writer)
Add a writer to the logger.
logger_builder & with_buffer_size(std::size_t size)
Set buffer size.
common::VoidResult add_writer(log_writer_ptr writer)
Definition logger.cpp:265
common::VoidResult log(common::interfaces::log_level level, const std::string &message) override
Log a message with specified level (ILogger interface)
Definition logger.cpp:378
const std::string & error_message() const
void example_write_ahead_logging()
void example_basic_critical_writer()
void example_hybrid_writer()
void example_error_handling()
void example_production_setup()
Synchronous wrapper for critical log messages to prevent loss.
File writer for logging to files with optional buffering.
High-performance, thread-safe logging system with asynchronous capabilities.
Builder pattern implementation for flexible logger configuration kcenon.
Rotating file writer with size and time-based rotation.
Configuration for critical log writer.