25 std::string Logger::getCurrentTimestamp() noexcept
27 const auto now = std::chrono::system_clock::now();
28 const std::time_t time = std::chrono::system_clock::to_time_t(now);
30 localtime_r(&time, &tm);
32 std::ostringstream oss;
33 oss << std::put_time(&tm,
"%Y-%m-%d %H:%M:%S");
37 void Logger::log(
const Level level,
const std::string& message,
const std::source_location& location)
noexcept
39 if (level >= _log_level)
41 std::scoped_lock lock(_log_mutex);
43 const std::string filename = std::filesystem::path(location.file_name()).filename().string();
44 const std::string file_line = filename +
":" + std::to_string(location.line());
46 std::ostringstream oss;
47 oss <<
"[" << getCurrentTimestamp() <<
"] " <<
"[" << std::setw(7) << std::left <<
getLevelString(level)
48 <<
"] " <<
"[" << std::setw(30) << std::left << file_line <<
"] " << message << std::endl;
50 std::cerr << oss.str();
52 if (_log_file && _log_file->is_open())
54 *_log_file << oss.str();
61 std::scoped_lock lock(_log_mutex);
63 std::ofstream file(filePath, std::ios::out | std::ios::trunc);
66 return std::unexpected(
"Unable to open log file: " + filePath);
69 _log_file = std::move(file);
Enum class representing the log levels.
Thread-safe logger class for handling logging operations.
void log(Level level, const std::string &message, const std::source_location &location=std::source_location::current()) noexcept
Logs a message with a specific log level and source location.
std::expected< void, std::string > logToFile(const std::string &filePath) noexcept
Sets the log file path to log messages to a file.
Header file for the logging system.
std::string getLevelString(const Level level) noexcept
Converts a log level enum value to its string representation.
Logger logger
Externally available logger object.