1. import java.io.BufferedReader;
  2. import java.io.FileReader;
  3. import java.io.IOException;
  4. import java.util.ArrayList;
  5. import java.util.List;
  6. import java.util.regex.Matcher;
  7. import java.util.regex.Pattern;
  8. public class LogErrorScanner {
  9. public static List<String> scanLogFile(String filePath) {
  10. List<String> errors = new ArrayList<>();
  11. try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
  12. String line;
  13. Pattern errorPattern = Pattern.compile("ERROR|Exception|Failed"); //Basic error keyword regex
  14. while ((line = reader.readLine()) != null) {
  15. Matcher matcher = errorPattern.matcher(line);
  16. if (matcher.find()) {
  17. errors.add(line); // Add the line to the list
  18. }
  19. }
  20. } catch (IOException e) {
  21. System.err.println("Error reading file: " + e.getMessage());
  22. }
  23. return errors;
  24. }
  25. public static void main(String[] args) {
  26. // Example usage:
  27. String logFilePath = "sample.log"; // Replace with your log file path
  28. List<String> errorLines = scanLogFile(logFilePath);
  29. if (errorLines.isEmpty()) {
  30. System.out.println("No errors found in the log file.");
  31. } else {
  32. System.out.println("Errors found in the log file:");
  33. for (String error : errorLines) {
  34. System.out.println(error);
  35. }
  36. }
  37. }
  38. }

Add your comment