kassner / log-parser
PHP Log Parser Library
Installs: 327 639
Dependents: 12
Suggesters: 0
Security: 0
Stars: 339
Watchers: 18
Forks: 64
Open Issues: 1
Requires
- php: >=7.4.0
README
Parse your Apache/Nginx/Varnish/HAProxy logs into PHP objects to programatically handle the data.
Install
composer require kassner/log-parser:~2.2
Usage
$parser = new \Kassner\LogParser\LogParser(); $lines = file('/var/log/apache2/access.log', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); foreach ($lines as $line) { $entry = $parser->parse($line); }
The $entry
object will hold all data parsed. If the line does not match the defined format, a \Kassner\LogParser\FormatException
will be thrown.
object(Kassner\LogParser\SimpleLogEntry)#4 (8) { ["host"]=> string(14) "193.191.216.76" ["logname"]=> string(1) "-" ["user"]=> string(8) "www-data" ["stamp"]=> int(1390794676) ["time"]=> string(26) "27/Jan/2014:04:51:16 +0100" ["request"]=> string(53) "GET /wp-content/uploads/2013/11/whatever.jpg HTTP/1.1" ["status"]=> string(3) "200" ["responseBytes"]=> string(5) "58678" }
Customizations
Log format
You may customize the log format (by default it matches the Apache common log format)
# default Nginx format: $parser->setFormat('%h %l %u %t "%r" %>s %O "%{Referer}i" \"%{User-Agent}i"');
Supported format strings
Here is the full list of log format strings supported by Apache, and whether they are supported by the library :
Beware: You should really read the notes when using a option that is marked with a
X
on theSupported?
column.
Custom formats
See #50 (comment)
Entry object
Before 2.0.0
it was possible to overwrite the entry object returned by overwriting the createEntry
method. With strict types, this is no longer possible, so instead you have to use the newly created interfaces.
First, create two new classes, your entry object and a factory that is responsible of creating it:
class MyEntry implements \Kassner\LogParser\LogEntryInterface { } class MyEntryFactory implements \Kassner\LogParser\LogEntryFactoryInterface { public function create(array $data): \Kassner\LogParser\LogEntryInterface { // @TODO implement your code here to return a instance of MyEntry } }
And then provide the factory as the second argument to the LogParser
constructor:
$factory = new MyEntryFactory(); $parser = new \Kassner\LogParser\LogParser(null, $factory); $entry = $parser->parse('193.191.216.76 - www-data [27/Jan/2014:04:51:16 +0100] "GET /wp-content/uploads/2013/11/whatever.jpg HTTP/1.1" 200 58678');
$entry
will be an instance of MyEntry
.