<?php
/**
* Flags anomalies in log files for scheduled runs with graceful failure handling.
*
* @param string $logFilePath The path to the log file.
* @param array $anomalyRules An array of anomaly rules. Each rule should be an array
* with 'pattern' (regex) and 'threshold' (integer).
* @param string $outputFile The path to the output file for flagged anomalies.
* @return bool True on success, false on failure.
*/
function flagLogAnomalies(string $logFilePath, array $anomalyRules, string $outputFile): bool
{
try {
// Validate input
if (!file_exists($logFilePath)) {
throw new InvalidArgumentException("Log file not found: $logFilePath");
}
if (!is_array($anomalyRules) || empty($anomalyRules)) {
throw new InvalidArgumentException("Anomaly rules must be a non-empty array.");
}
if (!is_string($outputFile)) {
throw new InvalidArgumentException("Output file must be a string.");
}
$anomalies = [];
// Read the log file line by line
if (($handle = fopen($logFilePath, "r")) !== FALSE) {
while (($line = fgets($handle)) !== FALSE) {
foreach ($anomalyRules as $rule) {
$pattern = $rule['pattern'];
$threshold = $rule['threshold'];
if (preg_match($pattern, $line)) {
$anomalies[] = [
'line' => $line,
'rule' => $rule,
];
}
}
}
fclose($handle);
} else {
throw new RuntimeException("Failed to open log file: $logFilePath");
}
// Write anomalies to the output file
if (file_put_contents($outputFile, json_encode($anomalies), FILE_APPEND | LOCK_EX) === FALSE) {
throw new RuntimeException("Failed to write anomalies to output file: $outputFile");
}
return true;
} catch (Exception $e) {
error_log("Error flagging log anomalies: " . $e->getMessage());
return false;
}
}
Add your comment