Logger System 0.1.3
High-performance C++20 thread-safe logging system with asynchronous capabilities
Loading...
Searching...
No Matches
main.cpp File Reference

Logger crash protection demonstration. More...

#include <iostream>
#include <thread>
#include <chrono>
#include <random>
#include <vector>
#include <memory>
#include <atomic>
#include <fstream>
#include "interfaces/logger_crash_safety.h"
#include "logger/logger.h"
#include "logger/writers/console_writer.h"
#include "logger/writers/file_writer.h"
#include <kcenon/common/interfaces/logger_interface.h>
Include dependency graph for main.cpp:

Go to the source code of this file.

Functions

void simulate_logger_crash ()
 
void simulate_file_corruption ()
 
void simulate_disk_full ()
 
void normal_logging_task (int task_id, std::shared_ptr< logger > logger_instance)
 
void heavy_logging_task (int task_id, std::shared_ptr< logger > logger_instance)
 
void potentially_crashing_logging_task (int task_id, std::shared_ptr< logger > logger_instance)
 
void on_logger_crash (const std::string &logger_name)
 
void flush_main_logger ()
 
void backup_main_logger (const std::string &backup_path)
 
void save_emergency_state ()
 
int main ()
 

Variables

std::atomic< bool > logging_active {true}
 
std::atomic< int > logs_written {0}
 
std::atomic< int > emergency_logs {0}
 

Detailed Description

Logger crash protection demonstration.

Definition in file main.cpp.

Function Documentation

◆ backup_main_logger()

void backup_main_logger ( const std::string & backup_path)
Examples
crash_protection/main.cpp.

Definition at line 155 of file main.cpp.

155 {
156 std::cout << "[BACKUP] Creating emergency backup: " << backup_path << std::endl;
157
158 // Copy current log file to backup location
159 std::ifstream source("./logs/application.log", std::ios::binary);
160 std::ofstream backup(backup_path, std::ios::binary);
161 backup << source.rdbuf();
162
163 std::cout << "[OK] Backup created successfully" << std::endl;
164}

Referenced by main().

Here is the caller graph for this function:

◆ flush_main_logger()

void flush_main_logger ( )
Examples
crash_protection/main.cpp.

Definition at line 151 of file main.cpp.

151 {
152 std::cout << "[FLUSH] Emergency flush of main logger" << std::endl;
153}

Referenced by main().

Here is the caller graph for this function:

◆ heavy_logging_task()

void heavy_logging_task ( int task_id,
std::shared_ptr< logger > logger_instance )
Examples
crash_protection/main.cpp.

Definition at line 80 of file main.cpp.

80 {
81 std::cout << "[LOG] Heavy logging task " << task_id << " starting" << std::endl;
82
83 for (int i = 0; i < 20; ++i) {
84 std::string large_message = "Heavy Task " + std::to_string(task_id) +
85 " - Large log entry " + std::to_string(i) +
86 " with lots of data: " + std::string(100, 'X');
87
88 logger_instance->log(ci::log_level::debug, large_message);
89 logs_written.fetch_add(1);
90
91 if (i % 5 == 0) {
92 logger_instance->log(ci::log_level::warning,
93 "Checkpoint " + std::to_string(i) + " for task " + std::to_string(task_id));
94 }
95
96 std::this_thread::sleep_for(std::chrono::milliseconds(25));
97 }
98
99 std::cout << "[OK] Heavy logging task " << task_id << " completed" << std::endl;
100}
std::atomic< int > logs_written
Definition main.cpp:37

References logs_written.

Referenced by main().

Here is the caller graph for this function:

◆ main()

int main ( )

Definition at line 172 of file main.cpp.

172 {
173 std::cout << "=== Logger System Crash Protection Demo ===" << std::endl;
174 std::cout << "This demo shows comprehensive logging crash protection mechanisms\n" << std::endl;
175
176 // Create logs directory
177 system("mkdir -p ./logs");
178
179 // Step 1: Initialize logger crash protection
180 std::cout << "--- Step 1: Initialize Logger Crash Protection ---" << std::endl;
181
182 auto& logger_safety = logger_crash_safety::instance();
183 logger_safety.initialize(logger_crash_safety_level::standard,
184 "./logs/emergency.log", 2000);
185
186 logger_safety.set_auto_backup(true, 3000);
187 logger_safety.set_max_emergency_entries(500);
188
189 std::cout << "[OK] Logger crash protection initialized" << std::endl;
190
191 // Step 2: Create and configure logger with crash protection
192 std::cout << "\n--- Step 2: Create Logger with Crash Protection ---" << std::endl;
193
194 auto main_logger = std::make_shared<logger>(true); // async mode
195 main_logger->add_writer(std::make_unique<console_writer>());
196 main_logger->add_writer(std::make_unique<file_writer>("./logs/application.log"));
197 main_logger->set_level(ci::log_level::debug);
198 main_logger->start();
199
200 // Register logger for crash protection
201 {
202 scoped_logger_crash_protection logger_protection("MainLogger",
204 [](const std::string& path) { backup_main_logger(path); });
205
206 std::cout << "[OK] Logger created and protected" << std::endl;
207
208 // Step 3: Test normal logging operations
209 std::cout << "\n--- Step 3: Normal Logging Operations ---" << std::endl;
210
211 main_logger->log(ci::log_level::info, std::string("Logger crash protection demo started"));
212 main_logger->log(ci::log_level::debug, std::string("Debug information available"));
213 main_logger->log(ci::log_level::warning, std::string("This is a warning message"));
214
215 // Step 4: Multi-threaded logging stress test
216 std::cout << "\n--- Step 4: Multi-threaded Logging Stress Test ---" << std::endl;
217
218 std::vector<std::thread> logging_threads;
219
220 // Normal logging threads
221 for (int i = 0; i < 3; ++i) {
222 logging_threads.emplace_back(normal_logging_task, i, main_logger);
223 }
224
225 // Heavy logging threads
226 for (int i = 3; i < 5; ++i) {
227 logging_threads.emplace_back(heavy_logging_task, i, main_logger);
228 }
229
230 // Wait for normal operations
231 for (auto& t : logging_threads) {
232 t.join();
233 }
234 logging_threads.clear();
235
236 std::cout << "[OK] Multi-threaded stress test completed" << std::endl;
237
238 // Step 5: Test file recovery mechanisms
239 std::cout << "\n--- Step 5: File Recovery Test ---" << std::endl;
240
241 // Create a corrupted file for testing
243
244 // Test corruption detection
245 if (log_file_recovery::is_corrupted("./logs/corrupted.log")) {
246 std::cout << "[DETECT] Corruption detected in test file" << std::endl;
247
248 // Attempt recovery
249 if (log_file_recovery::recover_file("./logs/corrupted.log",
250 "./logs/recovered.log")) {
251 std::cout << "[OK] File recovery successful" << std::endl;
252 } else {
253 std::cout << "[FAIL] File recovery failed" << std::endl;
254 }
255 }
256
257 // Test backup with checksum
258 log_file_recovery::create_backup_with_checksum("./logs/application.log",
259 "./logs/application_checksum_backup.log");
260
261 // Verify integrity
262 if (log_file_recovery::verify_integrity("./logs/application_checksum_backup.log",
263 "./logs/application_checksum_backup.log.checksum")) {
264 std::cout << "[OK] Backup integrity verified" << std::endl;
265 }
266
267 // Step 6: Test emergency logging
268 std::cout << "\n--- Step 6: Emergency Logging Test ---" << std::endl;
269
270 logger_safety.emergency_log("INFO", "Testing emergency logging system");
271 logger_safety.emergency_log("WARNING", "Emergency logging is signal-safe");
272 logger_safety.emergency_log("ERROR", "This log survives crashes");
273 emergency_logs.fetch_add(3);
274
275 // Step 7: Test risky operations with crash protection
276 std::cout << "\n--- Step 7: Risky Operations Test ---" << std::endl;
277 std::cout << "[WARN] Some operations may trigger crash protection" << std::endl;
278
279 // Submit risky logging tasks
280 for (int i = 10; i < 15; ++i) {
281 logging_threads.emplace_back(potentially_crashing_logging_task, i, main_logger);
282 }
283
284 // Wait for risky operations
285 for (auto& t : logging_threads) {
286 t.join();
287 }
288
289 // Step 8: Test async logger crash safety
290 std::cout << "\n--- Step 8: Async Logger Crash Safety ---" << std::endl;
291
292 async_logger_crash_safety::configure_async_safety("MainLogger", 2000, true);
293 async_logger_crash_safety::set_overflow_handler("MainLogger",
294 [](size_t dropped) {
295 std::cout << "[WARN] Buffer overflow: " << dropped << " messages dropped" << std::endl;
296 });
297
298 // Generate burst of logs to test overflow handling
299 for (int i = 0; i < 1000; ++i) {
300 main_logger->log(ci::log_level::debug, "Burst log " + std::to_string(i));
301 }
302
303 // Force flush to test emergency procedures
304 logger_safety.force_flush_all();
305 logger_safety.force_backup_all();
306
307 } // scoped_logger_crash_protection goes out of scope here
308
309 // Step 9: Display crash protection statistics
310 std::cout << "\n--- Step 9: Crash Protection Statistics ---" << std::endl;
311
312 auto stats = logger_safety.get_stats();
313 std::cout << "Emergency Log Statistics:" << std::endl;
314 std::cout << " Total emergency logs: " << stats.total_emergency_logs << std::endl;
315 std::cout << " Successful flushes: " << stats.successful_flushes << std::endl;
316 std::cout << " Failed flushes: " << stats.failed_flushes << std::endl;
317 std::cout << " Backup count: " << stats.backup_count << std::endl;
318
319 std::cout << "\nApplication Statistics:" << std::endl;
320 std::cout << " Total logs written: " << logs_written.load() << std::endl;
321 std::cout << " Emergency logs: " << emergency_logs.load() << std::endl;
322 std::cout << " Logging active: " << (logging_active.load() ? "Yes" : "No") << std::endl;
323
324 // Step 10: Test recovery capabilities
325 std::cout << "\n--- Step 10: Recovery Test ---" << std::endl;
326
327 if (logger_safety.check_and_recover()) {
328 std::cout << "[OK] Recovery actions were taken" << std::endl;
329 } else {
330 std::cout << "[INFO] No recovery needed" << std::endl;
331 }
332
333 // Step 11: Graceful shutdown
334 std::cout << "\n--- Step 11: Graceful Shutdown ---" << std::endl;
335
336 main_logger->log(ci::log_level::info, std::string("Shutting down logger crash protection demo"));
337 main_logger->stop();
338
339 std::cout << "\n=== Demo Completed Successfully ===" << std::endl;
340 std::cout << "Key features demonstrated:" << std::endl;
341 std::cout << "[OK] Emergency logging (signal-safe)" << std::endl;
342 std::cout << "[OK] Automatic log flushing on crash" << std::endl;
343 std::cout << "[OK] Log file corruption detection and recovery" << std::endl;
344 std::cout << "[OK] Backup creation with integrity verification" << std::endl;
345 std::cout << "[OK] Async logger crash safety" << std::endl;
346 std::cout << "[OK] Multi-threaded logging protection" << std::endl;
347 std::cout << "[OK] RAII-based crash protection registration" << std::endl;
348 std::cout << "[OK] Buffer overflow handling" << std::endl;
349
350 return 0;
351}
std::atomic< bool > logging_active
Definition main.cpp:36
void simulate_file_corruption()
Definition main.cpp:46
void flush_main_logger()
Definition main.cpp:151
void heavy_logging_task(int task_id, std::shared_ptr< logger > logger_instance)
Definition main.cpp:80
void backup_main_logger(const std::string &backup_path)
Definition main.cpp:155
std::atomic< int > emergency_logs
Definition main.cpp:38
void potentially_crashing_logging_task(int task_id, std::shared_ptr< logger > logger_instance)
Definition main.cpp:102
void normal_logging_task(int task_id, std::shared_ptr< logger > logger_instance)
Definition main.cpp:64

References backup_main_logger(), emergency_logs, flush_main_logger(), heavy_logging_task(), logging_active, logs_written, normal_logging_task(), potentially_crashing_logging_task(), and simulate_file_corruption().

Here is the call graph for this function:

◆ normal_logging_task()

void normal_logging_task ( int task_id,
std::shared_ptr< logger > logger_instance )
Examples
crash_protection/main.cpp.

Definition at line 64 of file main.cpp.

64 {
65 std::cout << "[LOG] Logging task " << task_id << " starting" << std::endl;
66
67 for (int i = 0; i < 5; ++i) {
68 std::string message = "Task " + std::to_string(task_id) +
69 " - Log entry " + std::to_string(i);
70
71 logger_instance->log(ci::log_level::info, message);
72 logs_written.fetch_add(1);
73
74 std::this_thread::sleep_for(std::chrono::milliseconds(50));
75 }
76
77 std::cout << "[OK] Logging task " << task_id << " completed" << std::endl;
78}

References logs_written.

Referenced by main().

Here is the caller graph for this function:

◆ on_logger_crash()

void on_logger_crash ( const std::string & logger_name)
Examples
crash_protection/main.cpp.

Definition at line 141 of file main.cpp.

141 {
142 std::cout << "\n[ALERT] LOGGER CRASH DETECTED: " << logger_name << std::endl;
143 logging_active.store(false);
144
145 // Emergency logging
146 logger_crash_safety::instance().emergency_log("CRITICAL",
147 "Logger " + logger_name + " has crashed - emergency mode activated");
148 emergency_logs.fetch_add(1);
149}

References emergency_logs, and logging_active.

◆ potentially_crashing_logging_task()

void potentially_crashing_logging_task ( int task_id,
std::shared_ptr< logger > logger_instance )
Examples
crash_protection/main.cpp.

Definition at line 102 of file main.cpp.

102 {
103 std::cout << "[WARN] Risky logging task " << task_id << " starting" << std::endl;
104
105 std::random_device rd;
106 std::mt19937 gen(rd());
107 std::uniform_int_distribution<> crash_dist(1, 10);
108
109 for (int i = 0; i < 10; ++i) {
110 std::string message = "Risky Task " + std::to_string(task_id) +
111 " - Entry " + std::to_string(i);
112
113 logger_instance->log(ci::log_level::info, message);
114 logs_written.fetch_add(1);
115
116 // Random chance of causing issues
117 int outcome = crash_dist(gen);
118 if (outcome <= 7) {
119 // Normal execution
120 std::this_thread::sleep_for(std::chrono::milliseconds(30));
121 } else if (outcome == 8) {
122 // Simulate emergency condition
123 logger_crash_safety::instance().emergency_log("CRITICAL",
124 "Emergency condition detected in task " + std::to_string(task_id));
125 emergency_logs.fetch_add(1);
126 } else if (outcome == 9) {
127 // Simulate file corruption
129 break;
130 } else {
131 // Simulate crash
133 break;
134 }
135 }
136
137 std::cout << "[WARN] Risky logging task " + std::to_string(task_id) + " finished" << std::endl;
138}
void simulate_logger_crash()
Definition main.cpp:41

References emergency_logs, logs_written, simulate_file_corruption(), and simulate_logger_crash().

Referenced by main().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ save_emergency_state()

void save_emergency_state ( )
Examples
crash_protection/main.cpp.

Definition at line 166 of file main.cpp.

166 {
167 std::cout << "[SAVE] Saving emergency logger state..." << std::endl;
168 std::cout << "Logs written: " << logs_written.load() << std::endl;
169 std::cout << "Emergency logs: " << emergency_logs.load() << std::endl;
170}

References emergency_logs, and logs_written.

◆ simulate_disk_full()

void simulate_disk_full ( )
Examples
crash_protection/main.cpp.

Definition at line 56 of file main.cpp.

56 {
57 std::cout << "[CRASH] Simulating disk full scenario..." << std::endl;
58 // Try to write a large amount of data to simulate disk full
59 logger_crash_safety::instance().emergency_log("ERROR",
60 "Disk space critical - switching to emergency logging mode");
61}

◆ simulate_file_corruption()

void simulate_file_corruption ( )
Examples
crash_protection/main.cpp.

Definition at line 46 of file main.cpp.

46 {
47 std::cout << "[CRASH] Simulating log file corruption..." << std::endl;
48 // Create a corrupted log file
49 std::ofstream corrupted_file("./logs/corrupted.log", std::ios::binary);
50 corrupted_file << "CORRUPTED_HEADER";
51 corrupted_file.write("\x00\x00\x00\x00", 4); // Null bytes
52 corrupted_file << "INVALID_LOG_DATA";
53 corrupted_file.close();
54}

Referenced by main(), and potentially_crashing_logging_task().

Here is the caller graph for this function:

◆ simulate_logger_crash()

void simulate_logger_crash ( )
Examples
crash_protection/main.cpp.

Definition at line 41 of file main.cpp.

41 {
42 std::cout << "[CRASH] Simulating logger system crash..." << std::endl;
43 std::raise(SIGTERM);
44}

Referenced by potentially_crashing_logging_task().

Here is the caller graph for this function:

Variable Documentation

◆ emergency_logs

std::atomic<int> emergency_logs {0}

◆ logging_active

std::atomic<bool> logging_active {true}
Examples
crash_protection/main.cpp.

Definition at line 36 of file main.cpp.

36{true};

Referenced by main(), and on_logger_crash().

◆ logs_written

std::atomic<int> logs_written {0}