日志轮转通过监控文件大小或时间周期,自动重命名并创建新日志文件,结合备份数量限制与归档策略,防止磁盘占满。

在C++项目中,尤其是长时间运行的服务程序,日志文件会不断增长,若不加以管理,容易耗尽磁盘空间或影响排查效率。因此,实现日志轮转(Log Rotation)和文件归档(Archiving)是必要的。下面介绍一种轻量、实用的实现方式,不依赖第三方库,适合嵌入中小型系统。
日志轮转的核心是:当当前日志文件达到指定大小,或按时间周期(如每天)触发时,将当前文件重命名或移动,然后创建新的日志文件继续写入。归档可以进一步将旧日志压缩或移至归档目录。
关键点:
使用std::ofstream写日志,每次写入前检查文件大小。若超过阈值(如10MB),关闭当前流,重命名原文件并打开新文件。
立即学习“C++免费学习笔记(深入)”;
示例代码片段:
#include <fstream>
#include <filesystem>
#include <string>
<p>class LogRotator {
std::ofstream logFile;
std::string basePath; // 如 "app.log"
size_t maxSize; // 字节,如 10 <em> 1024 </em> 1024
int maxBackups;</p><p>public:
LogRotator(const std::string& path, size_t size = 10<em>1024</em>1024, int backups = 5)
: basePath(path), maxSize(size), maxBackups(backups) {
openNewFile();
}</p><pre class='brush:php;toolbar:false;'>void write(const std::string& msg) {
if (shouldRotate()) {
rotate();
}
if (logFile.is_open()) {
logFile << msg << "\n";
logFile.flush(); // 可选:确保立即写入
}
}private: void openNewFile() { logFile.open(basePath, std::ios::app); }
bool shouldRotate() {
if (!logFile.is_open()) return false;
logFile.seekp(0, std::ios::end);
return logFile.tellp() >= maxSize;
}
void rotate() {
logFile.close();
// 从最旧的开始,删除或重命名备份文件
for (int i = maxBackups - 1; i >= 0; --i) {
std::string src = (i == 0) ? basePath : (basePath + "." + std::to_string(i));
std::string dst = basePath + "." + std::to_string(i + 1);
if (std::filesystem::exists(src)) {
if (i + 1 >= maxBackups) {
std::filesystem::remove(src); // 超出数量限制,删除
} else {
std::filesystem::rename(src, dst);
}
}
}
openNewFile();
}};
除了大小,也可按天轮转。例如每天生成一个日志文件,文件名包含日期(app.log.2024-04-05)。可结合std::chrono和std::put_time获取当前日期。
归档可定期将7天前的日志打包为zip或gz,并移至 }
void archiveOldLogs(const std::string& logPattern, int daysOld) {
auto now = std::chrono::system_clock::now();
auto cutoff = now - std::chrono::hours(24 * daysOld);
<pre class='brush:php;toolbar:false;'>for (const auto& entry : std::filesystem::directory_iterator(".")) {
if (entry.path().filename().string().find(logPattern) != std::string::npos) {
auto fileTime = entry.last_write_time();
if (fileTime < cutoff) {
std::string zipName = entry.path().string() + ".gz";
std::string cmd = "gzip -f " + entry.path().string();
std::system(cmd.c_str());
}
}
}
注意:调用系统命令需确保环境支持gzip等工具。
若多线程写日志,需加锁保护write()方法。可用std::mutex简单保护整个写入流程。
频繁检查文件大小可能影响性能。可设置写入计数器,每100次检查一次大小,或仅在写入前判断是否接近阈值。
对于高吞吐场景,建议采用异步日志队列,将轮转逻辑放入独立线程处理。
基本上就这些。C++标准库加已足够实现基本轮转与归档。不复杂但容易忽略细节,比如文件重命名冲突、权限、异常处理等,实际部署时需加强健壮性。
以上就是C++文件I/O中实现日志轮转和文件归档的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号