#include #include #include #include #include #include #include namespace vl::logging { namespace fs = std::filesystem; static std::string formatTimestamp(const std::chrono::system_clock::time_point& tp) { const auto tt = std::chrono::system_clock::to_time_t(tp); std::tm tm{}; #if defined(_WIN32) localtime_s(&tm, &tt); #else localtime_r(&tt, &tm); #endif char buf[32]; std::strftime(buf, sizeof(buf), "%F %T", &tm); return std::string{buf}; } static std::string ymdOf(const std::chrono::system_clock::time_point& tp) { const auto tt = std::chrono::system_clock::to_time_t(tp); std::tm tm{}; #if defined(_WIN32) localtime_s(&tm, &tt); #else localtime_r(&tt, &tm); #endif char buf[16]; std::strftime(buf, sizeof(buf), "%F", &tm); // YYYY-MM-DD return std::string{buf}; } FileSink::FileSink(std::string basePath, std::uintmax_t maxBytes) : base_(std::move(basePath)), maxBytes_(maxBytes) { fs::path p(base_); if (p.has_parent_path()) fs::create_directories(p.parent_path()); } std::string FileSink::dateOf(const std::chrono::system_clock::time_point& tp) { return ymdOf(tp); } std::string FileSink::filenameFor(const std::string& base, std::string_view date, int index) { // base_YYYY-MM-DD_index.log return std::format("{}_{}_{}.log", base, date, index); } void FileSink::openCurrent() { const auto name = filenameFor(base_, currentDate_, index_); out_.close(); out_.clear(); out_.open(name, std::ios::out | std::ios::app | std::ios::binary); if (!out_) throw std::runtime_error(std::format("FileSink: cannot open '{}'", name)); try { written_ = fs::file_size(name); } catch (...) { written_ = 0; } } void FileSink::rotateToDate(std::string newDate) { currentDate_ = std::move(newDate); index_ = 1; openCurrent(); } void FileSink::ensureOpen(const Message& msg) { const auto msgDate = dateOf(msg.ts); if (!out_.is_open()) { currentDate_ = msgDate; index_ = 1; openCurrent(); return; } if (msgDate != currentDate_) { rotateToDate(msgDate); return; } if (maxBytes_ > 0 && written_ >= maxBytes_) { ++index_; openCurrent(); } } void FileSink::write(const Message& msg) { ensureOpen(msg); const auto line = std::format("{} {} {:>5} {}\n", formatTimestamp(msg.ts), msg.prefix, toString(msg.level), msg.text); out_ << line; written_ += static_cast(line.size()); out_.flush(); } } // namespace vl::log