9MetricsLogger::MetricsLogger() : running(true) {
11 logFile.open(
"guardian_log.txt", std::ios::out | std::ios::app);
13 if (!logFile.is_open()) {
14 std::cerr <<
"Warning: Could not open log file, logging to console only\n";
18 logThread = std::thread(&MetricsLogger::processLogs,
this);
27 if (logThread.joinable()) {
32 if (logFile.is_open()) {
42std::string MetricsLogger::getCurrentTimestamp() {
43 auto now = std::chrono::system_clock::now();
44 auto time_t_now = std::chrono::system_clock::to_time_t(now);
45 auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
46 now.time_since_epoch()) % 1000;
49 ss << std::put_time(std::localtime(&time_t_now),
"%Y-%m-%d %H:%M:%S");
50 ss <<
'.' << std::setfill(
'0') << std::setw(3) << ms.count();
56 entry.timestamp = getCurrentTimestamp();
57 entry.category = category;
58 entry.message = message;
62 std::lock_guard<std::mutex> lock(queueMutex);
70void MetricsLogger::processLogs() {
72 std::unique_lock<std::mutex> lock(queueMutex);
75 queueCV.wait(lock, [
this] {
return !logQueue.empty() || !running; });
78 while (!logQueue.empty()) {
79 LogEntry entry = logQueue.front();
86 std::string logLine =
"[" + entry.timestamp +
"] " +
87 entry.category +
": " + entry.message;
90 std::cout << logLine <<
'\n';
93 if (logFile.is_open()) {
94 logFile << logLine <<
'\n';
101 queueCV.notify_all();
104 if (logFile.is_open()) {
111 std::unique_lock<std::mutex> lock(queueMutex);
112 queueCV.wait(lock, [
this] {
return logQueue.empty(); });
115 if (logFile.is_open()) {
Thread-safe, non-blocking logging system for real-time applications.
Singleton logger with non-blocking, thread-safe operation.
~MetricsLogger()
Destructor - stops logging thread.
static MetricsLogger & getInstance()
Gets singleton instance.
void flush()
Flushes all pending logs (blocking - use only at shutdown)
void logEvent(const std::string &category, const std::string &message)
Logs an event (non-blocking, thread-safe)