fix race condition in logging.hpp

This commit is contained in:
Mars 2025-05-02 13:07:02 -04:00
parent f03ca4f293
commit c33ab763e6
Signed by: pupbrained
GPG key ID: 874E22DF2F9DFCB5
2 changed files with 13 additions and 6 deletions

View file

@ -4,6 +4,7 @@
#include <filesystem> // std::filesystem::path
#include <format> // std::format
#include <ftxui/screen/color.hpp> // ftxui::Color
#include <mutex> // std::{mutex, lock_guard}
#include <print> // std::print
#include <utility> // std::forward
@ -17,11 +18,14 @@
namespace util::logging {
using types::usize, types::u8, types::i32, types::i64, types::CStr, types::String, types::StringView, types::Array,
types::Option, types::None;
types::Option, types::None, types::Mutex, types::LockGuard;
inline fn GetLogMutex() -> Mutex& {
static Mutex LogMutexInstance;
return LogMutexInstance;
}
// Store all compile-time constants in a struct
struct LogLevelConst {
// ANSI color codes
// clang-format off
static constexpr Array<StringView, 16> COLOR_CODE_LITERALS = {
"\033[38;5;0m", "\033[38;5;1m", "\033[38;5;2m", "\033[38;5;3m",
@ -31,20 +35,17 @@ namespace util::logging {
};
// clang-format on
// ANSI formatting constants
static constexpr const char* RESET_CODE = "\033[0m";
static constexpr const char* BOLD_START = "\033[1m";
static constexpr const char* BOLD_END = "\033[22m";
static constexpr const char* ITALIC_START = "\033[3m";
static constexpr const char* ITALIC_END = "\033[23m";
// Log level text constants
static constexpr StringView DEBUG_STR = "DEBUG";
static constexpr StringView INFO_STR = "INFO ";
static constexpr StringView WARN_STR = "WARN ";
static constexpr StringView ERROR_STR = "ERROR";
// Log level color constants
static constexpr ftxui::Color::Palette16 DEBUG_COLOR = ftxui::Color::Palette16::Cyan;
static constexpr ftxui::Color::Palette16 INFO_COLOR = ftxui::Color::Palette16::Green;
static constexpr ftxui::Color::Palette16 WARN_COLOR = ftxui::Color::Palette16::Yellow;
@ -163,6 +164,8 @@ namespace util::logging {
using namespace std::chrono;
using std::filesystem::path;
const LockGuard lock(GetLogMutex());
const auto nowTp = system_clock::now();
const std::time_t nowTt = system_clock::to_time_t(nowTp);
std::tm localTm;

View file

@ -5,6 +5,7 @@
#include <future> // std::future (Future)
#include <map> // std::map (Map)
#include <memory> // std::shared_ptr and std::unique_ptr (SharedPointer, UniquePointer)
#include <mutex> // std::mutex and std::lock_guard (Mutex, LockGuard)
#include <optional> // std::optional (Option)
#include <string> // std::string (String, StringView)
#include <string_view> // std::string_view (StringView)
@ -34,6 +35,9 @@ namespace util::types {
using Exception = std::exception; ///< Standard exception type.
using Mutex = std::mutex; ///< Mutex type for synchronization.
using LockGuard = std::lock_guard<Mutex>; ///< RAII-style lock guard for mutexes.
inline constexpr std::nullopt_t None = std::nullopt; ///< Represents an empty optional value.
/**