首页 > 解决方案 > 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]: =======================================================================

在日志文件中定期删除内容的最佳方法是什么?

标签: phpfilelogging

解决方案


打开文件并循环播放文件。
当您发现“太旧”的日期时,请删除该行。

然后将新数据保存在日志文件中。

$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.');

请先在副本上执行此操作,因为它是未经测试的代码。


推荐阅读