Linux/c++ 日志轮换方案
我有一个记录器系统,它基本上是一种以线程安全的方式将数据写入 std::clog 的奇特方式。
我还将 std::clog
重定向到这样的文件:
int main() {
std::ofstream logfile(config::logname, std::ios::app);
std::streambuf *const old_buffer = std::clog.rdbuf(logfile.rdbuf());
// .. the guts of the application
std::clog.rdbuf(old_buffer);
}
这很好用...但是,我的应用程序还生成大量日志。 我想知道正确轮换日志文件的好方法是什么。 有没有一种安全的方法可以通过 cron 任务切换文件? 我猜不会。
我能想到的唯一肯定有效的方法是,如果我让应用程序本身打开一个新文件,并将 clog 的 rdbuf 重定向到该文件,同时保留日志互斥体。 但这感觉像是一个廉价的解决方案,我需要检查一下是否需要经常轮换日志才能使其有效。 必须有更好的方法。
I have a logger system which basically is a fancy way of writing my data to std::clog in a thread safe way.
I also, redirect std::clog
to a file like this:
int main() {
std::ofstream logfile(config::logname, std::ios::app);
std::streambuf *const old_buffer = std::clog.rdbuf(logfile.rdbuf());
// .. the guts of the application
std::clog.rdbuf(old_buffer);
}
This works great... however, my application also produces a very large amount of logs. I was wondering what would be a good way to properly rotate my log files. Is there a safe way to switch out the file via a cron task? I would guess no.
The only thing I can think of that would definitely work is if I had the application itself open a new file, and redirect the rdbuf of clog to that while holding the logging mutex. But that feels like a cheap solution, and I would need to check so see if it is time to rotate logs fairly often for it to be effective. There has got to be a better way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 /etc/logrotate.conf 和/或 /etc/logrotate.d/ 中配置的内置日志轮换方法 - 通常让 logrotate 向您的应用程序发送 SIGUSR1 作为关闭并重新打开所有应用程序的信号日志文件。
You can use the built-in log rotation method configured in /etc/logrotate.conf and/or /etc/logrotate.d/ - it's common to have logrotate send your app a SIGUSR1 as a signal to close and re-open all your log files.
或者只使用 syslog 而不是您的自定义日志记录方案,并且日志无论如何都会由 logrotate 轮换。 -- 取决于它的配置方式,但在大多数桌面/服务器系统上,它已经设置为轮换它们。
Or just use syslog instead of your custom logging scheme and the logs get rotated by logrotate anyway. -- depending on how it's configured but on most desktop/server systems it's already set to rotate them.
您可以使用类似于以下内容的内容,并以任何方式将日志文件移走(logrotate、cron 脚本等)(提供 Cish 示例,应该很容易转换)
移动后写入文件是安全的,所以不需要额外小心
You can use something similar to the following, and move the log file away whichever way (logrotate, cron script, etc.) (providing Cish sample, should be easily convertible)
It is safe to write to a file after it has been moved, so there's no need for extra caution