import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class LogAnomalyDetector {
private static final int ANOMALY_THRESHOLD = 3; // Define anomaly threshold
private static final String LOG_FILE_PATH = "logfile.txt"; //Default logfile path
public static void main(String[] args) {
if (args.length > 0) {
LOG_FILE_PATH = args[0]; //Use argument if provided
}
try {
List<String> logEntries = readLogFile(LOG_FILE_PATH);
detectAndFlagAnomalies(logEntries);
} catch (IOException e) {
System.err.println("Error reading log file: " + e.getMessage());
}
}
/**
* Reads log entries from a file.
* @return A list of log entries.
* @throws IOException If an error occurs while reading the file.
*/
public static List<String> readLogFile(String filePath) throws IOException {
List<String> logEntries = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = reader.readLine()) != null) {
logEntries.add(line);
}
}
return logEntries;
}
/**
* Detects and flags anomalies in the log entries.
* @param logEntries A list of log entries.
*/
public static void detectAndFlagAnomalies(List<String> logEntries) {
Map<String, Integer> wordCounts = new HashMap<>();
// Count word occurrences in each log entry
for (String entry : logEntries) {
String[] words = entry.toLowerCase().split("\\s+"); // Split into words, convert to lowercase
for (String word : words) {
wordCounts.put(word, wordCounts.getOrDefault(word, 0) + 1);
}
}
// Identify anomalies based on word frequency
for (String entry : logEntries) {
int anomalyCount = 0;
String[] words = entry.toLowerCase().split("\\s+");
for (String word : words) {
if (wordCounts.getOrDefault(word, 0) > ANOMALY_THRESHOLD) {
anomalyCount++;
}
}
if (anomalyCount > 0) {
System.out.println("Anomaly detected: " + entry);
}
}
}
}
Add your comment