<?php
/**
* Indexes timestamp content for diagnostics.
*
* @param string $directory The directory containing the timestamp files.
* @param string $flag The optional flag to apply (e.g., 'all', 'errors', 'warnings'). Defaults to 'all'.
* @param string $outputFile The output file to write the indexed data to. Defaults to 'index.txt'.
* @return bool True on success, false on failure.
*/
function indexTimestamps(string $directory, string $flag = 'all', string $outputFile = 'index.txt'): bool
{
if (!is_dir($directory)) {
error_log("Error: Directory '$directory' does not exist.");
return false;
}
$files = scandir($directory);
if ($files === false) {
error_log("Error: Could not read directory '$directory'.");
return false;
}
$indexedData = [];
foreach ($files as $file) {
if ($file == '.' || $file == '..') {
continue;
}
if (pathinfo($file, PATHINFO_EXTENSION) !== 'log') {
continue; // Only process log files
}
$filePath = $directory . '/' . $file;
if (file_exists($filePath)) {
try {
$content = file_get_contents($filePath);
if ($content === false) {
error_log("Error: Could not read file '$filePath'.");
continue;
}
$lines = explode("\n", $content);
foreach ($lines as $line) {
$line = trim($line); // Remove leading/trailing whitespace
if (empty($line)) {
continue;
}
if ($flag === 'all' || strpos($line, 'ERROR') !== false || strpos($line, 'Exception') !== false) {
$indexedData[] = ['file' => $file, 'timestamp' => date('Y-m-d H:i:s', strtotime(substr($line, 0, 19))), 'content' => $line];
} elseif ($flag === 'errors' && strpos($line, 'ERROR') !== false) {
$indexedData[] = ['file' => $file, 'timestamp' => date('Y-m-d H:i:s', strtotime(substr($line, 0, 19))), 'content' => $line];
} elseif ($flag === 'warnings' && strpos($line, 'WARNING') !== false) {
$indexedData[] = ['file' => $file, 'timestamp' => date('Y-m-d H:i:s', strtotime(substr($line, 0, 19))), 'content' => $line];
}
}
} catch (Exception $e) {
error_log("Error processing file '$filePath': " . $e->getMessage());
}
}
}
if (empty($indexedData)) {
error_log("No data found for specified flag.");
return false;
}
$output = '';
foreach ($indexedData as $data) {
$output .= "File: " . $data['file'] . "\n";
$output .= "Timestamp: " . $data['timestamp'] . "\n";
$output .= "Content: " . $data['content'] . "\n\n";
}
file_put_contents($outputFile, $output);
return true;
}
?>
Add your comment