Boost log 限制日志文件大小 和 数量
作者:互联网
使用过 python 日志模块, 滚动设置很好用, 能限制日志文件数量 , 不至于长时间运行爆掉硬盘 .
网上找了一圈, 也没找到想要的结果, 有人还自己实现了限制文件数量…太麻烦了
最后自己试出来了, 分享一下:
MyLog::MyLog()
{
_fileCount = 4;
_fileSize = 1;
_logLevel = boost::log::trivial::severity_level::info;
FMT = "%Y-%m-%d %H:%M:%S";
}
MyLog::~MyLog()
{
}
void MyLog::init(const std::string& filename)
{
_filename = filename;
boost::filesystem::path filepath = boost::filesystem::complete(_filename);
boost::filesystem::path dir = filepath.parent_path();
if (boost::filesystem::exists(dir) == false)
{
boost::filesystem::create_directories(dir);
}
auto fmt =
(
expr::stream
<< expr::format_date_time< boost::posix_time::ptime >("TimeStamp", FMT)
<< " [" << boost::log::trivial::severity
<< "] " << expr::smessage
);
auto consoleSink = boost::log::add_console_log
( std::clog,
keywords::filter = expr::attr< trvl::severity_level >("Severity") >= (trvl::severity_level)_logLevel,
keywords::auto_flush = true,
keywords::format = fmt
);
auto sink = boost::log::add_file_log
(
keywords::open_mode = std::ios::app,
keywords::file_name = filename, // 写入的日志文件名, 如 log.log
keywords::target_file_name = "log_%Y%m%d-%N.log", // 备份日志文件命名格式, 必须
keywords::rotation_size = _fileSize * 1024 * 100, // 日志文件大小 100KB
keywords::filter = expr::attr< trvl::severity_level >("Severity") >= (trvl::severity_level)_logLevel,
keywords::auto_flush = true,
keywords::format = fmt
);
sink->locked_backend()->set_file_collector(sinks::file::make_collector(
keywords::target = "", // 备份日志文件保存目录
keywords::max_size = _fileSize * _fileCount * 1024 * 100 //所有日志加起来的最大大小
));
boost::log::add_common_attributes();
}
我限制了文件数量 4 个, 结果与设置一致, 算上 log.log 始终是四个文件
标签:文件大小,log,Boost,filename,keywords,日志,boost,MyLog 来源: https://blog.csdn.net/wn0112/article/details/112538953