1. import java.util.HashMap;
  2. import java.util.Map;
  3. import java.util.regex.Matcher;
  4. import java.util.regex.Pattern;
  5. public class LogMapper {
  6. /**
  7. * Maps log fields from a log line using regex.
  8. * @param logLine The log line to parse.
  9. * @param fieldRegex A map where keys are field names and values are regex patterns.
  10. * @return A map containing the extracted field values, or null if parsing fails.
  11. */
  12. public static Map<String, String> mapLogFields(String logLine, Map<String, String> fieldRegex) {
  13. Map<String, String> fields = new HashMap<>();
  14. if (logLine == null || logLine.isEmpty() || fieldRegex == null || fieldRegex.isEmpty()) {
  15. return null; // Handle null or empty input
  16. }
  17. for (Map.Entry<String, String> entry : fieldRegex.entrySet()) {
  18. String fieldName = entry.getKey();
  19. String regex = entry.getValue();
  20. Pattern pattern = Pattern.compile(regex);
  21. Matcher matcher = pattern.matcher(logLine);
  22. if (matcher.find()) {
  23. fields.put(fieldName, matcher.group());
  24. } else {
  25. // Field not found in the log line
  26. fields.put(fieldName, null); // Or handle missing fields differently (e.g., throw an exception)
  27. }
  28. }
  29. return fields;
  30. }
  31. public static void main(String[] args) {
  32. // Example Usage
  33. String logLine = "2023-10-27 10:00:00 [INFO] User: John Doe, ID: 12345 - Message: User logged in";
  34. Map<String, String> fieldRegex = new HashMap<>();
  35. fieldRegex.put("timestamp", "(\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2})");
  36. fieldRegex.put("level", "\[(\\w+)\]");
  37. fieldRegex.put("user", "User: (\\w+ \\w+)");
  38. fieldRegex.put("id", "ID: \\d+");
  39. fieldRegex.put("message", "Message: (.*)");
  40. Map<String, String> mappedFields = mapLogFields(logLine, fieldRegex);
  41. if (mappedFields != null) {
  42. System.out.println(mappedFields);
  43. } else {
  44. System.out.println("Error: Invalid log line or field regex.");
  45. }
  46. }
  47. }

Add your comment