PHP读取nginx日志文件显示到表格中

评论1,022

PHP读取nginx日志,以下是 PHP 代码示例,可以读取 NGINX 日志文件并按照格式显示到 HTML 表格中:

<?php
// 定义日志文件路径
$nginx_log_file = "/var/log/nginx/access.log";

// 打开日志文件
$file_handle = fopen($nginx_log_file, "r");

// 输出 HTML 表格头部
echo "<table border='1'>
    <tr>
        <th>IP 地址</th>
        <th>访问时间</th>
        <th>请求方法</th>
        <th>请求 URL</th>
        <th>HTTP 版本</th>
        <th>状态码</th>
        <th>返回字节数</th>
        <th>来源 URL</th>
        <th>User Agent</th>
    </tr>";

// 逐行读取日志文件
while (!feof($file_handle)) {
    $line = fgets($file_handle);

    // 解析日志字段
    $log_parts = explode(' ', $line);
    $ip_address = $log_parts[0];
    $access_time = $log_parts[3]." ".$log_parts[4];
    $request_method = $log_parts[5];
    $request_url = $log_parts[6];
    $http_version = $log_parts[7];
    $status_code = $log_parts[8];
    $return_bytes = $log_parts[9];
    $referer_url = $log_parts[10];
    $user_agent = implode(" ", array_slice($log_parts, 11));
    
    // 输出 HTML 表格行
    echo "<tr>
            <td>".$ip_address."</td>
            <td>".$access_time."</td>
            <td>".$request_method."</td>
            <td>".$request_url."</td>
            <td>".$http_version."</td>
            <td>".$status_code."</td>
            <td>".$return_bytes."</td>
            <td>".$referer_url."</td>
            <td>".$user_agent."</td>
        </tr>";
}

// 输出 HTML 表格尾部
echo "</table>";

// 关闭日志文件
fclose($file_handle);

此代码假定日志文件路径为 $nginx_log_file 变量所定义的文件路径。代码将该文件打开,逐行读取每条日志记录,并使用 PHP 的字符串函数来解析各个字段。然后将这些字段输出到 HTML 表格中。最后关闭日志文件。

请注意,此示例代码仅适用于默认的 NGINX 日志格式。如果您使用的不是默认格式,则需要根据日志格式更改解析代码。

 最后更新:2023-6-23

发表评论