import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LogMapper {
/**
* Maps log fields from a log line using regex.
* @param logLine The log line to parse.
* @param fieldRegex A map where keys are field names and values are regex patterns.
* @return A map containing the extracted field values, or null if parsing fails.
*/
public static Map<String, String> mapLogFields(String logLine, Map<String, String> fieldRegex) {
Map<String, String> fields = new HashMap<>();
if (logLine == null || logLine.isEmpty() || fieldRegex == null || fieldRegex.isEmpty()) {
return null; // Handle null or empty input
}
for (Map.Entry<String, String> entry : fieldRegex.entrySet()) {
String fieldName = entry.getKey();
String regex = entry.getValue();
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(logLine);
if (matcher.find()) {
fields.put(fieldName, matcher.group());
} else {
// Field not found in the log line
fields.put(fieldName, null); // Or handle missing fields differently (e.g., throw an exception)
}
}
return fields;
}
public static void main(String[] args) {
// Example Usage
String logLine = "2023-10-27 10:00:00 [INFO] User: John Doe, ID: 12345 - Message: User logged in";
Map<String, String> fieldRegex = new HashMap<>();
fieldRegex.put("timestamp", "(\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2})");
fieldRegex.put("level", "\[(\\w+)\]");
fieldRegex.put("user", "User: (\\w+ \\w+)");
fieldRegex.put("id", "ID: \\d+");
fieldRegex.put("message", "Message: (.*)");
Map<String, String> mappedFields = mapLogFields(logLine, fieldRegex);
if (mappedFields != null) {
System.out.println(mappedFields);
} else {
System.out.println("Error: Invalid log line or field regex.");
}
}
}
Add your comment