1. import java.io.BufferedReader;
  2. import java.io.FileReader;
  3. import java.io.IOException;
  4. import java.util.ArrayList;
  5. import java.util.HashMap;
  6. import java.util.List;
  7. import java.util.Map;
  8. public class LogAnomalyDetector {
  9. private static final int ANOMALY_THRESHOLD = 3; // Define anomaly threshold
  10. private static final String LOG_FILE_PATH = "logfile.txt"; //Default logfile path
  11. public static void main(String[] args) {
  12. if (args.length > 0) {
  13. LOG_FILE_PATH = args[0]; //Use argument if provided
  14. }
  15. try {
  16. List<String> logEntries = readLogFile(LOG_FILE_PATH);
  17. detectAndFlagAnomalies(logEntries);
  18. } catch (IOException e) {
  19. System.err.println("Error reading log file: " + e.getMessage());
  20. }
  21. }
  22. /**
  23. * Reads log entries from a file.
  24. * @return A list of log entries.
  25. * @throws IOException If an error occurs while reading the file.
  26. */
  27. public static List<String> readLogFile(String filePath) throws IOException {
  28. List<String> logEntries = new ArrayList<>();
  29. try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
  30. String line;
  31. while ((line = reader.readLine()) != null) {
  32. logEntries.add(line);
  33. }
  34. }
  35. return logEntries;
  36. }
  37. /**
  38. * Detects and flags anomalies in the log entries.
  39. * @param logEntries A list of log entries.
  40. */
  41. public static void detectAndFlagAnomalies(List<String> logEntries) {
  42. Map<String, Integer> wordCounts = new HashMap<>();
  43. // Count word occurrences in each log entry
  44. for (String entry : logEntries) {
  45. String[] words = entry.toLowerCase().split("\\s+"); // Split into words, convert to lowercase
  46. for (String word : words) {
  47. wordCounts.put(word, wordCounts.getOrDefault(word, 0) + 1);
  48. }
  49. }
  50. // Identify anomalies based on word frequency
  51. for (String entry : logEntries) {
  52. int anomalyCount = 0;
  53. String[] words = entry.toLowerCase().split("\\s+");
  54. for (String word : words) {
  55. if (wordCounts.getOrDefault(word, 0) > ANOMALY_THRESHOLD) {
  56. anomalyCount++;
  57. }
  58. }
  59. if (anomalyCount > 0) {
  60. System.out.println("Anomaly detected: " + entry);
  61. }
  62. }
  63. }
  64. }

Add your comment