1. <?php
  2. /**
  3. * Indexes timestamp content for diagnostics.
  4. *
  5. * @param string $directory The directory containing the timestamp files.
  6. * @param string $flag The optional flag to apply (e.g., 'all', 'errors', 'warnings'). Defaults to 'all'.
  7. * @param string $outputFile The output file to write the indexed data to. Defaults to 'index.txt'.
  8. * @return bool True on success, false on failure.
  9. */
  10. function indexTimestamps(string $directory, string $flag = 'all', string $outputFile = 'index.txt'): bool
  11. {
  12. if (!is_dir($directory)) {
  13. error_log("Error: Directory '$directory' does not exist.");
  14. return false;
  15. }
  16. $files = scandir($directory);
  17. if ($files === false) {
  18. error_log("Error: Could not read directory '$directory'.");
  19. return false;
  20. }
  21. $indexedData = [];
  22. foreach ($files as $file) {
  23. if ($file == '.' || $file == '..') {
  24. continue;
  25. }
  26. if (pathinfo($file, PATHINFO_EXTENSION) !== 'log') {
  27. continue; // Only process log files
  28. }
  29. $filePath = $directory . '/' . $file;
  30. if (file_exists($filePath)) {
  31. try {
  32. $content = file_get_contents($filePath);
  33. if ($content === false) {
  34. error_log("Error: Could not read file '$filePath'.");
  35. continue;
  36. }
  37. $lines = explode("\n", $content);
  38. foreach ($lines as $line) {
  39. $line = trim($line); // Remove leading/trailing whitespace
  40. if (empty($line)) {
  41. continue;
  42. }
  43. if ($flag === 'all' || strpos($line, 'ERROR') !== false || strpos($line, 'Exception') !== false) {
  44. $indexedData[] = ['file' => $file, 'timestamp' => date('Y-m-d H:i:s', strtotime(substr($line, 0, 19))), 'content' => $line];
  45. } elseif ($flag === 'errors' && strpos($line, 'ERROR') !== false) {
  46. $indexedData[] = ['file' => $file, 'timestamp' => date('Y-m-d H:i:s', strtotime(substr($line, 0, 19))), 'content' => $line];
  47. } elseif ($flag === 'warnings' && strpos($line, 'WARNING') !== false) {
  48. $indexedData[] = ['file' => $file, 'timestamp' => date('Y-m-d H:i:s', strtotime(substr($line, 0, 19))), 'content' => $line];
  49. }
  50. }
  51. } catch (Exception $e) {
  52. error_log("Error processing file '$filePath': " . $e->getMessage());
  53. }
  54. }
  55. }
  56. if (empty($indexedData)) {
  57. error_log("No data found for specified flag.");
  58. return false;
  59. }
  60. $output = '';
  61. foreach ($indexedData as $data) {
  62. $output .= "File: " . $data['file'] . "\n";
  63. $output .= "Timestamp: " . $data['timestamp'] . "\n";
  64. $output .= "Content: " . $data['content'] . "\n\n";
  65. }
  66. file_put_contents($outputFile, $output);
  67. return true;
  68. }
  69. ?>

Add your comment