|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Startwind\Inventorio\Collector\System\Logs; |
|
4
|
|
|
|
|
5
|
|
|
use Startwind\Inventorio\Collector\Collector; |
|
6
|
|
|
|
|
7
|
|
|
class LogrotateCollector implements Collector |
|
8
|
|
|
{ |
|
9
|
|
|
public function getIdentifier(): string |
|
10
|
|
|
{ |
|
11
|
|
|
return 'SystemLogLogrotate'; |
|
12
|
|
|
} |
|
13
|
|
|
|
|
14
|
|
|
public function collect(): array |
|
15
|
|
|
{ |
|
16
|
|
|
return [ |
|
17
|
|
|
'logfiles' => $this->findLogFiles() |
|
18
|
|
|
]; |
|
19
|
|
|
} |
|
20
|
|
|
|
|
21
|
|
|
function findLogFiles(): array |
|
|
|
|
|
|
22
|
|
|
{ |
|
23
|
|
|
// Only search under /var/log |
|
24
|
|
|
$searchPath = '/var/log'; |
|
25
|
|
|
|
|
26
|
|
|
// Paths to logrotate configuration files |
|
27
|
|
|
$logrotateConfs = ['/etc/logrotate.conf', ...glob('/etc/logrotate.d/*')]; |
|
28
|
|
|
|
|
29
|
|
|
// Step 1: Find all .log files under /var/log |
|
30
|
|
|
$allLogs = []; |
|
31
|
|
|
$iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($searchPath, \FilesystemIterator::SKIP_DOTS)); |
|
32
|
|
|
foreach ($iterator as $file) { |
|
33
|
|
|
if (preg_match('/\.log$/', $file->getFilename())) { |
|
34
|
|
|
$allLogs[] = realpath($file->getPathname()); |
|
35
|
|
|
} |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
// Step 2: Extract managed log file paths from logrotate configs |
|
39
|
|
|
$managedLogs = []; |
|
40
|
|
|
foreach ($logrotateConfs as $confFile) { |
|
41
|
|
|
if (!is_readable($confFile)) continue; |
|
|
|
|
|
|
42
|
|
|
$lines = file($confFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); |
|
|
|
|
|
|
43
|
|
|
foreach ($lines as $line) { |
|
44
|
|
|
// Look for lines that contain a log file path |
|
45
|
|
|
if (preg_match('#^\s*/[^\s{}]+\.log#', $line, $matches)) { |
|
46
|
|
|
$managedLogs[] = realpath(trim($matches[0])); |
|
47
|
|
|
} |
|
48
|
|
|
} |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
// Step 3: Filter out invalid paths and duplicates |
|
52
|
|
|
$allLogs = array_unique(array_filter($allLogs)); |
|
53
|
|
|
$managedLogs = array_unique(array_filter($managedLogs)); |
|
54
|
|
|
|
|
55
|
|
|
// Step 4: Return logs that are not listed in logrotate configs |
|
56
|
|
|
return [ |
|
57
|
|
|
'unmanaged' => array_values(array_diff($allLogs, $managedLogs)), |
|
58
|
|
|
'managed' => $managedLogs |
|
59
|
|
|
]; |
|
60
|
|
|
} |
|
61
|
|
|
} |
|
62
|
|
|
|
Adding explicit visibility (
private,protected, orpublic) is generally recommend to communicate to other developers how, and from where this method is intended to be used.