1. <?php
  2. /**
  3. * Attaches metadata to log files for maintenance tasks.
  4. *
  5. * @param string $logFilePath The path to the log file.
  6. * @param array $maintenanceLimits An array of maintenance task limits.
  7. * Example: ['max_lines' => 1000, 'max_size_kb' => 10240]
  8. * @return bool True on success, false on failure.
  9. */
  10. function attachMaintenanceMetadata(string $logFilePath, array $maintenanceLimits): bool
  11. {
  12. if (!file_exists($logFilePath)) {
  13. error_log("Log file not found: " . $logFilePath);
  14. return false;
  15. }
  16. // Define hardcoded maintenance limits
  17. $maxLines = $maintenanceLimits['max_lines'] ?? 1000; //default 1000 lines
  18. $maxSizeKb = $maintenanceLimits['max_size_kb'] ?? 10240; //default 10KB
  19. $fileHandle = fopen($logFilePath, 'r');
  20. if ($fileHandle === false) {
  21. error_log("Failed to open log file: " . $logFilePath);
  22. return false;
  23. }
  24. $fileSize = filesize($logFilePath);
  25. $lineCount = 0;
  26. if ($fileSize > $maxSizeKb * 1024) { // Convert KB to bytes
  27. error_log("Log file exceeds size limit (" . ($maxSizeKb * 1024) . "KB): " . $logFilePath);
  28. fclose($fileHandle);
  29. return false;
  30. }
  31. while (!feof($fileHandle)) {
  32. fgets($fileHandle); // Skip the header if any.
  33. $lineCount++;
  34. if ($lineCount > $maxLines) {
  35. error_log("Log file exceeds line limit (" . $maxLines . "): " . $logFilePath);
  36. fclose($fileHandle);
  37. return false;
  38. }
  39. }
  40. fclose($fileHandle);
  41. // Add metadata to a new file (e.g., maintenance_metadata.txt)
  42. $metadataFilePath = 'maintenance_metadata.txt';
  43. $metadataContent = "Log File: " . $logFilePath . "\n";
  44. $metadataContent .= "Line Count: " . $lineCount . "\n";
  45. $metadataContent .= "File Size: " . number_format($fileSize / (1024 * 1024), 2) . " MB\n"; //Format size in MB
  46. $metadataContent .= "Timestamp: " . date('Y-m-d H:i:s') . "\n";
  47. if (file_put_contents($metadataFilePath, $metadataContent) === false) {
  48. error_log("Failed to write metadata to file: " . $metadataFilePath);
  49. return false;
  50. }
  51. return true;
  52. }
  53. // Example Usage (replace with your log file path)
  54. $logFile = 'my_log_file.log';
  55. $maintenanceLimits = ['max_lines' => 2000, 'max_size_kb' => 20480];
  56. if (attachMaintenanceMetadata($logFile, $maintenanceLimits)) {
  57. echo "Metadata attached successfully.\n";
  58. } else {
  59. echo "Metadata attachment failed.\n";
  60. }
  61. ?>

Add your comment