Search⌘ K
AI Features

Solution: Logging Security Events

Explore how to implement logging for security events in Java by verifying user credentials and recording access attempts. Learn to initialize loggers, check authorized users, and log both successful and failed authentication events to ensure secure monitoring.

We'll cover the following...
Java 25
import java.util.logging.Logger;
import java.util.logging.Level;
import java.util.List;
record User(String username, String password) {}
public class LoginManager {
// Initialize the logger using the class name
private static final Logger logger = Logger.getLogger(LoginManager.class.getName());
private static final List<User> VALID_USERS = List.of(
new User("admin", "securePass"),
new User("manager", "bankOps123")
);
public boolean login(String username, String password) {
for (User user : VALID_USERS) {
// Check if both username and password match
if (user.username().equals(username) && user.password().equals(password)) {
// Log success as informational
logger.log(Level.INFO, "User " + username + " logged in successfully.");
return true;
}
}
// If we reach here, no match was found in the list
// Log failure as a warning to highlight potential security issues
logger.log(Level.WARNING, "Failed login attempt for user: " + username + ".");
return false;
}
public static void main(String[] args) {
LoginManager manager = new LoginManager();
manager.login("admin", "securePass"); // Logs INFO
manager.login("hacker", "wrong123"); // Logs WARNING
manager.login("manager", "bankOps123"); // Logs INFO
}
}
...