1. import java.util.regex.Matcher;
  2. import java.util.regex.Pattern;
  3. public class LogValidator {
  4. /**
  5. * Validates a log entry against a set of constraints.
  6. * @param logEntry The log entry string to validate.
  7. * @param usernameRegex Regular expression for username validation.
  8. * @param logLevelRegex Regular expression for log level validation.
  9. * @param messageLength The maximum length of the log message.
  10. * @return True if the log entry is valid, false otherwise.
  11. */
  12. public static boolean isValidLogEntry(String logEntry, String usernameRegex, String logLevelRegex, int messageLength) {
  13. // Validate username format
  14. Pattern usernamePattern = Pattern.compile(usernameRegex);
  15. Matcher usernameMatcher = usernamePattern.matcher(logEntry);
  16. if (!usernameMatcher.find()) {
  17. System.out.println("Invalid username format.");
  18. return false;
  19. }
  20. // Validate log level
  21. Pattern logLevelPattern = Pattern.compile(logLevelRegex);
  22. Matcher logLevelMatcher = logLevelPattern.matcher(logEntry);
  23. if (!logLevelMatcher.find()) {
  24. System.out.println("Invalid log level format.");
  25. return false;
  26. }
  27. // Validate message length
  28. if (logEntry.length() > messageLength) {
  29. System.out.println("Message exceeds maximum length.");
  30. return false;
  31. }
  32. // Add more constraints here as needed
  33. return true;
  34. }
  35. public static void main(String[] args) {
  36. // Example usage
  37. String logEntry1 = "user123 [INFO] This is a valid log message.";
  38. String logEntry2 = "invalid-user [ERROR] Short";
  39. String logEntry3 = "user456 [DEBUG] This is a very long log message that exceeds the maximum allowed length.";
  40. String usernameRegex = "^[a-zA-Z0-9]+$"; // Example username regex
  41. String logLevelRegex = "^(DEBUG|INFO|WARN|ERROR|FATAL)$"; // Example log level regex
  42. int messageLength = 100; // Example message length limit
  43. System.out.println("Log Entry 1 is valid: " + isValidLogEntry(logEntry1, usernameRegex, logLevelRegex, messageLength));
  44. System.out.println("Log Entry 2 is valid: " + isValidLogEntry(logEntry2, usernameRegex, logLevelRegex, messageLength));
  45. System.out.println("Log Entry 3 is valid: " + isValidLogEntry(logEntry3, usernameRegex, logLevelRegex, messageLength));
  46. }
  47. }

Add your comment