You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP读取过滤日志文件并输出最新10条指定记录的实现问题

PHP日志解析优化实现代码
<?php
// 定义日志文件路径
$logPath = 'logfile.log';
$matchedRecords = [];

// 校验文件读取权限
if (!is_readable($logPath)) {
    die('日志文件不存在或无读取权限');
}

$handler = fopen($logPath, 'r');
if (!$handler) {
    die('日志文件打开失败');
}

// 逐行读取处理日志
while (!feof($handler)) {
    $line = trim(fgets($handler));
    if (empty($line)) {
        continue;
    }

    // 精准匹配目标行,同时提取日期、时间、msg字段的JSON内容
    if (preg_match('/^(\d{2}\.\d{2}\.\d{4}) (\d{2}:\d{2}:\d{2}): .*name=QsoInfo:state.*msg=(\[.*\])/', $line, $matches)) {
        $date = $matches[1];
        $time = $matches[2];
        $msgJson = $matches[3];

        // 解析JSON提取call值,增加异常判断避免报错
        $msgData = json_decode($msgJson, true);
        if (json_last_error() === JSON_ERROR_NONE && isset($msgData[0]['call'])) {
            $callName = $msgData[0]['call'];
            $matchedRecords[] = [
                'date' => $date,
                'time' => $time,
                'name' => $callName
            ];
        }
    }
}
fclose($handler);

// 日志默认按正序存储(旧记录在前),反转后取前10条即为最新记录
$latestRecords = array_slice(array_reverse($matchedRecords), 0, 10);

// 按指定格式输出
foreach ($latestRecords as $record) {
    echo "Date ({$record['date']}) | Time ({$record['time']}) | Name ({$record['name']})<br>";
}
?>

核心优化说明

  • 替换原有宽松的关键词匹配逻辑,改为精准匹配含name=QsoInfo:state的日志行,避免无关行被误判
  • 采用正则表达式一次性提取日期、时间、msg的JSON内容,比手动拆分字符串更稳定,适配固定格式的日志场景
  • 新增JSON解析逻辑,正确提取msg字段中的call值,增加解析错误判断避免代码异常
  • 调整结果排序逻辑:日志默认按写入时间正序存储,反转匹配结果后截取前10条,即可得到最新的10条符合要求的记录
  • 按要求格式化输出结果,不再输出原始数组结构

内容的提问来源于stack exchange,提问作者KraggleGrag

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 20:12:04