import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LogValidator {
/**
* Validates a log entry against a set of constraints.
* @param logEntry The log entry string to validate.
* @param usernameRegex Regular expression for username validation.
* @param logLevelRegex Regular expression for log level validation.
* @param messageLength The maximum length of the log message.
* @return True if the log entry is valid, false otherwise.
*/
public static boolean isValidLogEntry(String logEntry, String usernameRegex, String logLevelRegex, int messageLength) {
// Validate username format
Pattern usernamePattern = Pattern.compile(usernameRegex);
Matcher usernameMatcher = usernamePattern.matcher(logEntry);
if (!usernameMatcher.find()) {
System.out.println("Invalid username format.");
return false;
}
// Validate log level
Pattern logLevelPattern = Pattern.compile(logLevelRegex);
Matcher logLevelMatcher = logLevelPattern.matcher(logEntry);
if (!logLevelMatcher.find()) {
System.out.println("Invalid log level format.");
return false;
}
// Validate message length
if (logEntry.length() > messageLength) {
System.out.println("Message exceeds maximum length.");
return false;
}
// Add more constraints here as needed
return true;
}
public static void main(String[] args) {
// Example usage
String logEntry1 = "user123 [INFO] This is a valid log message.";
String logEntry2 = "invalid-user [ERROR] Short";
String logEntry3 = "user456 [DEBUG] This is a very long log message that exceeds the maximum allowed length.";
String usernameRegex = "^[a-zA-Z0-9]+$"; // Example username regex
String logLevelRegex = "^(DEBUG|INFO|WARN|ERROR|FATAL)$"; // Example log level regex
int messageLength = 100; // Example message length limit
System.out.println("Log Entry 1 is valid: " + isValidLogEntry(logEntry1, usernameRegex, logLevelRegex, messageLength));
System.out.println("Log Entry 2 is valid: " + isValidLogEntry(logEntry2, usernameRegex, logLevelRegex, messageLength));
System.out.println("Log Entry 3 is valid: " + isValidLogEntry(logEntry3, usernameRegex, logLevelRegex, messageLength));
}
}
Add your comment