php - php 只删除日志文件中的部分内容
问题描述
在我最近的应用程序中,我必须编写一系列 cronjobs 并将它们记录到自定义日志文件中,这些日志文件包含异常的详细信息和/或显示每次执行的状态。
问题是我的日志文件越来越大,我想从文件中清除一些内容并保持苗条。比如说只在这个文件中保留最近 10 天的内容并清除旧的内容。
我的示例错误日志文件如下:
[2019-05-16 06:38:16 AM]: Catalog Import - Process started.
[2019-05-16 06:38:17 AM]: - Brands processed.
[2019-05-16 06:38:18 AM]: - Categories processed.
[2019-05-16 06:38:27 AM]: - Catalogues processed.
[2019-05-16 06:38:29 AM]: - CSV generated.
[2019-05-16 06:38:29 AM]: Catalog Import - Process completed.
[2019-05-16 06:38:29 AM]: =======================================================================
[2019-05-17 06:38:16 AM]: Catalog Import - Process started.
[2019-05-17 06:38:17 AM]: Exception - (json encoded response usually array stuffs)
[2019-05-17 06:38:18 AM]: - Categories processed.
[2019-05-17 06:38:27 AM]: - Catalogues processed.
[2019-05-17 06:38:29 AM]: Error - (json encoded response usually array stuffs)
[2019-05-17 06:38:29 AM]: Catalog Import - Process completed.
[2019-05-17 06:38:29 AM]: =======================================================================
在日志文件中定期删除内容的最佳方法是什么?
解决方案
打开文件并循环播放文件。
当您发现“太旧”的日期时,请删除该行。
然后将新数据保存在日志文件中。
$log_file = 'catalog_import.log';
// get the file contents as array.
$lines = file( $log_file);
if (!empty($lines)) {
foreach ($lines as $row => $line) {
// if older than 10 days.
if (time() - strtotime(substr($line, 1, 10)) > 60 * 60 * 24 * 10) {
unset($lines[$row]);
}
}
}
//write the filtered data to the file.
file_put_contents($log_file, implode("", $lines));
die('logs cleared successfully.');
请先在副本上执行此操作,因为它是未经测试的代码。
推荐阅读
- tfs - 如何使用 REST API 修改工作项的 BoardColumn 字段
- php - 如何在 Avada 子主题功能中覆盖 Fusion Element Container?
- c# - 通过 AD 服务主体进行 Azure SQL 身份验证
- python - 当列名在值中时,Pandas 拆分 DataFrame
- c++ - 通过本机 C++ 代码移动 UWP 应用程序窗口
- apache-beam - 如何在 Beam SQL shell 中添加 google cloud pubsub 作为源?
- sql - 更改表以增量添加 ID 值为空的主键记录
- python - 如何选择性地覆盖 Python 中的“==”行为?
- android - 如何从android NDK中的另一个c ++文件中读取常量
- python - 如何检索我刚刚上传的视频的 URL?