19 auto& inst = instance();
20 std::lock_guard<std::mutex> lock(inst.logMutex_);
22 inst.minLevel_ = minLevel;
24 if (!logFilePath.empty())
26 if (inst.logFile_.is_open())
27 inst.logFile_.close();
28 inst.logFile_.open(logFilePath, std::ios::app);
29 if (!inst.logFile_.is_open())
31 std::cerr <<
"[Logger] Failed to open log file: " << logFilePath << std::endl;
35 inst.logFile_ <<
"\n=== Logger initialized at " << getCurrentTimestamp()
36 <<
" ===" << std::endl;
43 auto& inst = instance();
44 std::lock_guard<std::mutex> lock(inst.logMutex_);
45 inst.minLevel_ = level;
50 auto& inst = instance();
51 std::lock_guard<std::mutex> lock(inst.logMutex_);
52 inst.consoleOutput_ = enabled;
57 auto& inst = instance();
58 std::lock_guard<std::mutex> lock(inst.logMutex_);
59 inst.timestamps_ = enabled;
64 auto& inst = instance();
65 std::lock_guard<std::mutex> lock(inst.logMutex_);
67 if (inst.logFile_.is_open())
69 inst.logFile_ <<
"=== Logger shutdown at " << getCurrentTimestamp() <<
" ===" << std::endl;
70 inst.logFile_.close();
78void Logger::log(
LogLevel level,
const std::string& message)
80 auto& inst = instance();
81 std::lock_guard<std::mutex> lock(inst.logMutex_);
84 if (level < inst.minLevel_)
90 std::ostringstream oss;
94 oss <<
"[" << getCurrentTimestamp() <<
"] ";
97 oss <<
"[" << getLevelString(level) <<
"] " << message;
98 std::string fullMessage = oss.str();
101 if (inst.consoleOutput_)
105 std::cerr << fullMessage << std::endl;
109 std::cout << fullMessage << std::endl;
114 if (inst.logFile_.is_open())
116 inst.logFile_ << fullMessage << std::endl;
117 inst.logFile_.flush();
121std::string Logger::getLevelString(
LogLevel level)
140std::string Logger::getCurrentTimestamp()
142 auto now = std::chrono::system_clock::now();
143 auto time = std::chrono::system_clock::to_time_t(now);
144 auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()) % 1000;
146 std::ostringstream oss;
148 localtime_r(&time, &tm);
149 oss << std::put_time(&tm,
"%Y-%m-%d %H:%M:%S");
150 oss <<
"." << std::setfill(
'0') << std::setw(3) << ms.count();
static void setLogLevel(LogLevel level)
Set minimum log level.
static void setConsoleOutput(bool enabled)
Enable or disable console output.
static void shutdown()
Shutdown logger and close log file.
static void setTimestamps(bool enabled)
Enable or disable timestamps in log messages.
static void init(const std::string &logFilePath="", LogLevel minLevel=LogLevel::INFO)
Initialize logger with optional file output.
@ FATAL
Fatal errors (application will terminate).
@ WARN
Warning messages (non-critical issues).
@ INFO
General informational messages.
@ ERROR
Error messages (recoverable failures).
@ DEBUG
Verbose debugging information.