<?php
/**
* Simple Log File Indexer
*
* Indexes lines from log files, providing a basic search interface.
*/
/**
* Indexes log files.
*
* @param array $log_files Array of log file paths.
* @return array Associative array where keys are line numbers and values are the corresponding lines.
*/
function indexLogFiles(array $log_files): array
{
$index = [];
foreach ($log_files as $log_file) {
if (file_exists($log_file)) {
$lines = file($log_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
for ($i = 0; $i < count($lines); $i++) {
$index[$i + 1] = $lines[$i]; // Line number starts from 1
}
} else {
error_log("Log file not found: " . $log_file);
}
}
return $index;
}
/**
* Searches the indexed log data.
*
* @param array $index The indexed log data.
* @param string $search_term The term to search for.
* @return array Array of line numbers containing the search term.
*/
function searchLog(array $index, string $search_term): array
{
$results = [];
$search_term = strtolower($search_term); // Case-insensitive search
foreach ($index as $line_number => $line) {
if (stripos($line, $search_term) !== false) {
$results[] = $line_number;
}
}
return $results;
}
// Example Usage
if (count($argv) < 2) {
echo "Usage: php index_logs.php <log_file1> <log_file2> ... [search_term]\n";
exit(1);
}
$log_files = array_slice($argv, 1);
$index = indexLogFiles($log_files);
if (isset($argv[2])) {
$search_term = strtolower($argv[2]);
$results = searchLog($index, $search_term);
if (!empty($results)) {
echo "Found in lines: " . implode(", ", $results) . "\n";
} else {
echo "No matches found for '" . $search_term . "'\n";
}
} else {
//Output index
foreach ($index as $line_number => $line) {
echo $line_number . ": " . $line . "\n";
}
}
?>
Add your comment