<?php
/**
* Attaches metadata to log files for maintenance tasks.
*
* @param string $logFilePath The path to the log file.
* @param array $maintenanceLimits An array of maintenance task limits.
* Example: ['max_lines' => 1000, 'max_size_kb' => 10240]
* @return bool True on success, false on failure.
*/
function attachMaintenanceMetadata(string $logFilePath, array $maintenanceLimits): bool
{
if (!file_exists($logFilePath)) {
error_log("Log file not found: " . $logFilePath);
return false;
}
// Define hardcoded maintenance limits
$maxLines = $maintenanceLimits['max_lines'] ?? 1000; //default 1000 lines
$maxSizeKb = $maintenanceLimits['max_size_kb'] ?? 10240; //default 10KB
$fileHandle = fopen($logFilePath, 'r');
if ($fileHandle === false) {
error_log("Failed to open log file: " . $logFilePath);
return false;
}
$fileSize = filesize($logFilePath);
$lineCount = 0;
if ($fileSize > $maxSizeKb * 1024) { // Convert KB to bytes
error_log("Log file exceeds size limit (" . ($maxSizeKb * 1024) . "KB): " . $logFilePath);
fclose($fileHandle);
return false;
}
while (!feof($fileHandle)) {
fgets($fileHandle); // Skip the header if any.
$lineCount++;
if ($lineCount > $maxLines) {
error_log("Log file exceeds line limit (" . $maxLines . "): " . $logFilePath);
fclose($fileHandle);
return false;
}
}
fclose($fileHandle);
// Add metadata to a new file (e.g., maintenance_metadata.txt)
$metadataFilePath = 'maintenance_metadata.txt';
$metadataContent = "Log File: " . $logFilePath . "\n";
$metadataContent .= "Line Count: " . $lineCount . "\n";
$metadataContent .= "File Size: " . number_format($fileSize / (1024 * 1024), 2) . " MB\n"; //Format size in MB
$metadataContent .= "Timestamp: " . date('Y-m-d H:i:s') . "\n";
if (file_put_contents($metadataFilePath, $metadataContent) === false) {
error_log("Failed to write metadata to file: " . $metadataFilePath);
return false;
}
return true;
}
// Example Usage (replace with your log file path)
$logFile = 'my_log_file.log';
$maintenanceLimits = ['max_lines' => 2000, 'max_size_kb' => 20480];
if (attachMaintenanceMetadata($logFile, $maintenanceLimits)) {
echo "Metadata attached successfully.\n";
} else {
echo "Metadata attachment failed.\n";
}
?>
Add your comment