引言回顾上一节同步日志器的核心架构LogLevel、LogMessage、Logger、LogFlush。本节目标将日志持久化到文件支持自动滚动按大小切割。设计思路1. 文件输出FileFlush职责将日志写入指定文件支持追加模式、可选自动刷盘auto_flush。2 滚动日志RollFileFlush需求单文件超过阈值时自动创建新文件避免磁盘占满。策略按照日期自动建立文件夹同一天的滚动日志在以当天命名的文件夹下。固定基础文件名递增序号每次滚动序号加1。3 工具类 UtilC17 filesystem使用std::filesystem实现目录创建、文件大小获取。代码实现1.Util.hppnamespace Util { namespace fs std::filesystem; inline bool Exists(const string path){ return fs::exists(path); } inline bool CreateDirectory(const string path){ if(path.empty()) return false; if(Exists(path)) return true; return fs::create_directories(path); } inline size_t Filesize(const string filename){ if(!fs::exists(filename)) return 0; return fs::file_size(filename); } inline string GetDirectory(const string path){ fs::path p(path); fs::path parent p.parent_path(); if(parent.empty()) return ; return parent.string()fs::path::preferred_separator; } inline string GetFilename(const string path){ return fs::path(path).filename().string(); } }2.FileFlush设计要点1.按日期分文件夹。2.跨天重新生成日期文件夹。代码class FileFlush : public LogFlush { private: string original_path_; // 原始路劲 FILE *fp_; // 文件描述符 bool auto_flush; // 手动刷盘 string actual_path_; // 实际路劲 string current_date_; static std::string GetCurrentDate() { auto now std::time(nullptr); std::tm tm_buf; localtime_r(now, tm_buf); char buf[16]; std::strftime(buf, sizeof(buf), %Y%m%d, tm_buf); return buf; } string BuildActualPath(const std::string date) { string dir Util::GetDirectory(original_path_); string base Util::GetFilename(original_path_); string date_dir dir date /; return date_dir base; } void OpenFileForDate(const std::string date) { if (fp_) { fclose(fp_); fp_ nullptr; } string date_dir Util::GetDirectory(BuildActualPath(date)); Util::CreateDirectory(date_dir); actual_path_ BuildActualPath(date); fp_ fopen(actual_path_.c_str(), a); if (!fp_) { perror(FileFlush: fopen failed); } current_date_ date; } public: FileFlush(const string filename, bool autoflush false) : original_path_(filename), auto_flush(autoflush), fp_(nullptr) { OpenFileForDate(GetCurrentDate()); } ~FileFlush() override { if (fp_) { fclose(fp_); } } void Flush(const string data, size_t len) override { if (!fp_) return; // 检查是否跨天 std::string today GetCurrentDate(); if (today ! current_date_) { OpenFileForDate(today); // 切换到新日期的文件 } fwrite(data.c_str(), 1, len, fp_); if (auto_flush) { fflush(fp_); } } };3.RollFileFlush设计要点1.按日期分文件夹。2.大小滚动3.程序重启不覆盖4.跨天重置序号代码// - 滚动日志输出类按文件大小滚动文件名格式为 basepath_YYYYMMDD_index.log // - 同一天内 index 从 0 开始递增超过 max_size 则 index 创建新文件 // - 跨天后自动重置 index 为当天最大序号1不会覆盖旧文件 // - 程序重启时扫描目录从当天已有最大序号的下一个开始避免覆盖 class RollFileFlush : public LogFlush { private: string base_path_; FILE *fp_; bool auto_flush; size_t max_size; size_t cur_size; size_t file_index; string current_date; private: string GetCurrentDate() { auto now std::time(nullptr); std::tm tm_buf; localtime_r(now, tm_buf); char buf[16]; std::strftime(buf, sizeof(buf), %Y%m%d, tm_buf); return buf; } // 获取当天日期文件夹的完整路径 string GetDateDirectory() { namespace fs std::filesystem; string dir Util::GetDirectory(base_path_); // logs/rolllog/ string basename fs::path(base_path_).filename().string(); // roll return dir current_date /; // logs/rolllog/20250412/ } size_t GetTodayMaxIndex() { namespace fs std::filesystem; string date_dir GetDateDirectory(); if (!fs::exists(date_dir)) return 0; // 目录不存在无历史文件 string prefix fs::path(base_path_).filename().string() _; size_t max_idx 0; for (auto entry : fs::directory_iterator(date_dir)) { if (!entry.is_regular_file()) continue; string fname entry.path().filename().string(); if (fname.find(prefix) 0 fname.size() prefix.size() fname.substr(fname.size() - 4) .log) { string num_str fname.substr(prefix.size(), fname.size() - prefix.size() - 4); size_t idx std::stoul(num_str); if (idx max_idx) max_idx idx; } } return max_idx; } void OpenNewFile() { namespace fs std::filesystem; if (fp_) { fclose(fp_); fp_ nullptr; } string today GetCurrentDate(); if (today ! current_date) { current_date today; file_index 0; } string date_dir GetDateDirectory(); Util::CreateDirectory(date_dir); file_index GetTodayMaxIndex() 1; string filename date_dir fs::path(base_path_).filename().string() _ std::to_string(file_index) .log; fp_ fopen(filename.c_str(), a); if (!fp_) { perror(RollFileFlush: fopen failed); return; } cur_size Util::Filesize(filename); } void Roll() { file_index; OpenNewFile(); } public: RollFileFlush(const string basepath, size_t maxsize, bool autoflush false) : base_path_(basepath), auto_flush(autoflush), max_size(maxsize), cur_size(0),fp_(nullptr) { string dir Util::GetDirectory(basepath); if (!dir.empty()) { Util::CreateDirectory(dir); } current_date GetCurrentDate(); file_index GetTodayMaxIndex() 1; OpenNewFile(); } ~RollFileFlush() { if (fp_) fclose(fp_); } void Flush(const string data, size_t len) override { if (!fp_) return; if (cur_size len max_size) { Roll(); } fwrite(data.c_str(), 1, len, fp_); cur_size len; if (auto_flush) { fflush(fp_); } } };遇到的问题1 段错误SIGSEGV通过调试发现现象程序退出时崩溃在fclose。原因fp_未初始化为nullptr导致在if(fp_)时误判。解决在构造函数初始化列表中将fp_ nullptr同时初始化其他成员cur_size0, file_index0。2 滚动只生成一个文件原因生成文件名仅精确到秒同一秒内多次滚动文件名相同导致以追加模式打开同一文件。解决采用递增序号每次滚动序号1保证唯一性。测试测试代码如下int main(){ mylog::Logger::ptr logger std::make_sharedmylog::Logger(console_logger); LOG_DEBUG(logger,hello:%s,age :%d ,lizhi,24); LOG_INFO(logger,hello:%s,age :%d ,lizhi,24); LOG_WARN(logger,hello:%s,age :%d ,lizhi,24); LOG_ERROR(logger,hello:%s,age :%d ,lizhi,24); LOG_FATAL(logger,hello:%s,age :%d ,lizhi,24); auto file_flush std::make_sharedmylog::FileFlush(logs/filelog/app.log); auto file_logger std::make_sharedmylog::Logger(file_logger,file_flush); LOG_INFO(file_logger, 普通文件日志程序启动); LOG_DEBUG(file_logger, 用户 %s 登录成功, 张三); auto roll_flush std::make_sharedmylog::RollFileFlush(logs/rolllog/roll,1000,false); auto roll_logger std::make_sharedmylog::Logger(roll_logger,roll_flush); for (int i 0; i 150; i) { LOG_INFO(roll_logger, 滚动测试消息编号 %d, i); } }运行结果如下成功生成文件日志和滚动文件日志补充输出日志加入时间因为日志是按日期分文件夹。所以此处只加入时分秒。LogMessage.hpp代码更新如下class LogMessage{ private: LogLevel::Level level_; //日志等級 char time_[64]; string filename_; //文件名 size_t line_; //行号 string message_; //消息体 size_t len_; //长度 public: //构造 LogMessage(LogLevel::Level level,const string filename,const size_t line, const string message): level_(level),filename_(filename),line_(line),message_(message),len_(message.size()){ time_t nowtime std::time(nullptr); struct tm tm_buf; localtime_r(nowtime,tm_buf); std::strftime(time_,sizeof(time_),%H:%M:%S,tm_buf); } //格式化 string format(){ return [LogLevel::Tostring(level_)][time_][filename_:std::to_string(line_)]\tmessage_\n; } };结语自己手敲一遍还是会遇到很多问题的。如何优化日志生成的文件夹敲了一下午。目前最新版已上传githubhttps://github.com/1710979882/Storage_of_asynchronous_logs