1. <?php
  2. /**
  3. * Flags anomalies in log files for scheduled runs with graceful failure handling.
  4. *
  5. * @param string $logFilePath The path to the log file.
  6. * @param array $anomalyRules An array of anomaly rules. Each rule should be an array
  7. * with 'pattern' (regex) and 'threshold' (integer).
  8. * @param string $outputFile The path to the output file for flagged anomalies.
  9. * @return bool True on success, false on failure.
  10. */
  11. function flagLogAnomalies(string $logFilePath, array $anomalyRules, string $outputFile): bool
  12. {
  13. try {
  14. // Validate input
  15. if (!file_exists($logFilePath)) {
  16. throw new InvalidArgumentException("Log file not found: $logFilePath");
  17. }
  18. if (!is_array($anomalyRules) || empty($anomalyRules)) {
  19. throw new InvalidArgumentException("Anomaly rules must be a non-empty array.");
  20. }
  21. if (!is_string($outputFile)) {
  22. throw new InvalidArgumentException("Output file must be a string.");
  23. }
  24. $anomalies = [];
  25. // Read the log file line by line
  26. if (($handle = fopen($logFilePath, "r")) !== FALSE) {
  27. while (($line = fgets($handle)) !== FALSE) {
  28. foreach ($anomalyRules as $rule) {
  29. $pattern = $rule['pattern'];
  30. $threshold = $rule['threshold'];
  31. if (preg_match($pattern, $line)) {
  32. $anomalies[] = [
  33. 'line' => $line,
  34. 'rule' => $rule,
  35. ];
  36. }
  37. }
  38. }
  39. fclose($handle);
  40. } else {
  41. throw new RuntimeException("Failed to open log file: $logFilePath");
  42. }
  43. // Write anomalies to the output file
  44. if (file_put_contents($outputFile, json_encode($anomalies), FILE_APPEND | LOCK_EX) === FALSE) {
  45. throw new RuntimeException("Failed to write anomalies to output file: $outputFile");
  46. }
  47. return true;
  48. } catch (Exception $e) {
  49. error_log("Error flagging log anomalies: " . $e->getMessage());
  50. return false;
  51. }
  52. }

Add your comment