1. <?php
  2. /**
  3. * Simple Log File Indexer
  4. *
  5. * Indexes lines from log files, providing a basic search interface.
  6. */
  7. /**
  8. * Indexes log files.
  9. *
  10. * @param array $log_files Array of log file paths.
  11. * @return array Associative array where keys are line numbers and values are the corresponding lines.
  12. */
  13. function indexLogFiles(array $log_files): array
  14. {
  15. $index = [];
  16. foreach ($log_files as $log_file) {
  17. if (file_exists($log_file)) {
  18. $lines = file($log_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
  19. for ($i = 0; $i < count($lines); $i++) {
  20. $index[$i + 1] = $lines[$i]; // Line number starts from 1
  21. }
  22. } else {
  23. error_log("Log file not found: " . $log_file);
  24. }
  25. }
  26. return $index;
  27. }
  28. /**
  29. * Searches the indexed log data.
  30. *
  31. * @param array $index The indexed log data.
  32. * @param string $search_term The term to search for.
  33. * @return array Array of line numbers containing the search term.
  34. */
  35. function searchLog(array $index, string $search_term): array
  36. {
  37. $results = [];
  38. $search_term = strtolower($search_term); // Case-insensitive search
  39. foreach ($index as $line_number => $line) {
  40. if (stripos($line, $search_term) !== false) {
  41. $results[] = $line_number;
  42. }
  43. }
  44. return $results;
  45. }
  46. // Example Usage
  47. if (count($argv) < 2) {
  48. echo "Usage: php index_logs.php <log_file1> <log_file2> ... [search_term]\n";
  49. exit(1);
  50. }
  51. $log_files = array_slice($argv, 1);
  52. $index = indexLogFiles($log_files);
  53. if (isset($argv[2])) {
  54. $search_term = strtolower($argv[2]);
  55. $results = searchLog($index, $search_term);
  56. if (!empty($results)) {
  57. echo "Found in lines: " . implode(", ", $results) . "\n";
  58. } else {
  59. echo "No matches found for '" . $search_term . "'\n";
  60. }
  61. } else {
  62. //Output index
  63. foreach ($index as $line_number => $line) {
  64. echo $line_number . ": " . $line . "\n";
  65. }
  66. }
  67. ?>

Add your comment