Code Coverage |
||||||||||
Classes and Traits |
Functions and Methods |
Lines |
||||||||
Total | |
0.00% |
0 / 1 |
|
0.00% |
0 / 3 |
CRAP | |
0.00% |
0 / 24 |
LogParser | |
0.00% |
0 / 1 |
|
0.00% |
0 / 3 |
56 | |
0.00% |
0 / 24 |
run | |
0.00% |
0 / 1 |
20 | |
0.00% |
0 / 9 |
|||
getLogFromFile | |
0.00% |
0 / 1 |
2 | |
0.00% |
0 / 6 |
|||
parseLogs | |
0.00% |
0 / 1 |
6 | |
0.00% |
0 / 9 |
1 | <?php |
2 | |
3 | namespace Qmp\Laravel\DockerScale\Retriever\Providers; |
4 | |
5 | use Qmp\Laravel\DockerScale\Models\HttpLog; |
6 | |
7 | class LogParser extends DockerAbstract |
8 | { |
9 | protected $model = HttpLog::class; |
10 | |
11 | protected $logPath = '/var/log/apache2'; |
12 | |
13 | protected $logFile = 'access.log'; |
14 | |
15 | protected $parsedLogFile = 'access-parsed.log'; |
16 | |
17 | protected $tmpLogFile = 'tmp.log'; |
18 | |
19 | public function run() |
20 | { |
21 | $this->removeOldData(); |
22 | $logs = []; |
23 | $scannedDirectory = array_diff(scandir($this->logPath), array('..', '.')); |
24 | foreach ($scannedDirectory as $directory) { |
25 | $completePathDir = $this->logPath . '/' . $directory; |
26 | if(is_dir($completePathDir) && file_exists($completePathDir . '/' . $this->logFile)) { |
27 | $content = $this->getLogFromFile($completePathDir . '/', $this->logFile); |
28 | $logs[$directory] = $this->parseLogs($content, $completePathDir . '/', $directory); |
29 | } |
30 | } |
31 | |
32 | return $logs; |
33 | } |
34 | |
35 | protected function getLogFromFile(string $pathDir, string $filename) |
36 | { |
37 | $filename = $pathDir . $filename; |
38 | $tmpLogFile = $pathDir . $this->tmpLogFile; |
39 | passthru("cp $filename $tmpLogFile && > $filename"); |
40 | |
41 | $contentFile = trim(file_get_contents($tmpLogFile)); |
42 | unlink($tmpLogFile); |
43 | |
44 | return explode("\n", $contentFile); |
45 | } |
46 | |
47 | protected function parseLogs(array $logs, string $directory, string $serviceName) |
48 | { |
49 | file_put_contents($directory . $this->parsedLogFile, implode("\n", $logs) . "\n", FILE_APPEND); |
50 | |
51 | return array_map(function($log) use ($serviceName) { |
52 | preg_match('/"(?P<ts>[0-9]+)" "(?P<distant>[^""]+)" "(?P<local>[^""]+)" "(?P<method>[^""]+)" "(?P<uri>[^""]+)" "(?P<code>[0-9]+)" "(?P<size>[0-9]+)" "(?P<time>[0-9]+)" "(?P<uri_from>[^""]+)" "(?P<user_agent>[^""]+)"/', $log, $test); |
53 | $result = array_intersect_key($test, array_flip(['ts', 'distant', 'local', 'method', 'uri', 'code', 'size', 'time', 'uri_from', 'user_agent'])); |
54 | if (!empty($result)) { |
55 | $result['service'] = $serviceName; |
56 | |
57 | return $this->save($result); |
58 | } |
59 | |
60 | return []; |
61 | |
62 | }, $logs); |
63 | } |
64 | } |