Which of the following code snippets correctly creates the logger and logs the warning message?
hard📝 Application Q15 of 15
Spring Boot - Logging
You want to create a logger in a Spring Boot class UserController that logs a warning message only when a user ID is missing. Which of the following code snippets correctly creates the logger and logs the warning message?
Aprivate static final Logger logger = LoggerFactory.getLogger(UserController.class);
public void checkUser(String userId) {
if (userId == null || userId.isEmpty()) {
logger.warn("User ID is missing");
}
}
BLogger logger = LoggerFactory.getLogger(UserController);
public void checkUser(String userId) {
if (userId == null) {
logger.error("User ID is missing");
}
}
Cprivate Logger logger = LoggerFactory.getLogger(UserController.class);
public void checkUser(String userId) {
if (userId.isEmpty()) {
logger.info("User ID is missing");
}
}
Dstatic final Logger logger = LoggerFactory.getLogger("UserController");
public void checkUser(String userId) {
if (userId == null) {
logger.debug("User ID is missing");
}
}
Step-by-Step Solution
Solution:
Step 1: Verify correct logger creation
private static final Logger logger = LoggerFactory.getLogger(UserController.class);
public void checkUser(String userId) {
if (userId == null || userId.isEmpty()) {
logger.warn("User ID is missing");
}
} uses private static final Logger with LoggerFactory.getLogger(UserController.class), which is the standard pattern.
Step 2: Check logging condition and level
private static final Logger logger = LoggerFactory.getLogger(UserController.class);
public void checkUser(String userId) {
if (userId == null || userId.isEmpty()) {
logger.warn("User ID is missing");
}
} checks if userId is null or empty and logs a warning with logger.warn(), which matches the requirement.
Final Answer:
private static final Logger logger = LoggerFactory.getLogger(UserController.class);
public void checkUser(String userId) {
if (userId == null || userId.isEmpty()) {
logger.warn("User ID is missing");
}
} -> Option A
Quick Check:
Use static final logger and logger.warn() for warnings [OK]
Quick Trick:Use logger.warn() for warnings and check null or empty [OK]
Common Mistakes:
Not using static final for logger
Logging wrong level (info, debug, error) for warnings
Not checking both null and empty strings
Master "Logging" in Spring Boot
9 interactive learning modes - each teaches the same concept differently