mvar / apache2-log-parser
Apache2 访问和错误日志解析器
v2.1.0
2015-12-20 16:57 UTC
Requires
- php: >=5.4
- mvar/log-parser: ~1.0
Requires (Dev)
- phpunit/phpunit: ~4.8
This package is not auto-updated.
Last update: 2024-09-14 13:55:52 UTC
README
安装
此库可以在 Packagist 上找到。推荐通过 Composer 安装。
composer require mvar/apache2-log-parser:dev-master
特性
- Apache2 日志行解析
- 访问日志
- 错误日志(目前,针对 Apache 2.2 及更早版本)
- 日志文件迭代器
- 即使是大文件也能保持低内存占用
用法
解析单个 Apache 访问日志行
<?php require __DIR__ . '/vendor/autoload.php'; use MVar\Apache2LogParser\AccessLogParser; // Access log format from your Apache configuration // It can be any of predefined `AccessLogParser::FORMAT_*` constants or custom string $parser = new AccessLogParser('%h %l %u %t "%r" %>s %O "%{Referer}i" "%{User-Agent}i"'); // String which you want to parse $line = '66.249.78.230 - - [29/Dec/2013:16:07:58 +0200] "GET /my-page/ HTTP/1.1" 200 2490 "-" ' . '"Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"'; var_export($parser->parseLine($line));
上述示例将输出
array ( 'remote_host' => '66.249.78.230', 'identity' => '-', 'remote_user' => '-', 'time' => '29/Dec/2013:16:07:58 +0200', 'request_line' => 'GET /my-page/ HTTP/1.1', 'response_code' => '200', 'bytes_sent' => '2490', 'request' => array ( 'method' => 'GET', 'path' => '/my-page/', 'protocol' => 'HTTP/1.1', ), 'request_headers' => array ( 'Referer' => '-', 'User-Agent' => 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)', ), )
遍历 Apache 日志文件
日志迭代器按行读取日志文件。这意味着可以使用低内存使用量解析大文件。
假设我们有一个 Apache 日志文件 access.log
,内容如下
192.168.25.1 - - [25/Jun/2012:14:26:05 -0700] "GET /favicon.ico HTTP/1.1" 404 498
192.168.25.1 - - [25/Jun/2012:14:26:05 -0700] "GET /icons/blank.gif HTTP/1.1" 200 438
要逐行解析整个日志文件,只需要创建一个新的迭代器,并传入文件名和解析器参数
<?php require __DIR__ . '/vendor/autoload.php'; use MVar\Apache2LogParser\AccessLogParser; use MVar\LogParser\LogIterator; $parser = new AccessLogParser(AccessLogParser::FORMAT_COMMON); foreach (new LogIterator('access.log', $parser) as $line => $data) { printf("%s %s\n", $data['request']['method'], $data['request']['path']); }
上述示例将输出
GET /favicon.ico
GET /icons/blank.gif
有关迭代器的更多信息,请访问 mvar/log-iterator 文档。
日期和时间格式化
默认情况下,日期和时间以原始字符串的形式返回。您可以通过两种方式更改此行为。首先,设置自定义格式字符串,将返回格式化后的日期字符串。其次,将时间格式设置为 true
,您将获得 \DateTime
对象。
$parser = new AccessLogParser(AccessLogParser::FORMAT_COMMON); // Set custom date and time format accepted by date() $parser->setTimeFormat('Y-m-d H:i:s'); // Set TRUE and you will get \DateTime object $parser->setTimeFormat(true);
未来版本待办事项
- 支持修改器
- 支持自定义时间格式
请随意提交 Pull Request :)