Introduction
Logging helps you see what your program is doing. Creating a logger in a class lets you record messages about the program's actions or errors.
Logging helps you see what your program is doing. Creating a logger in a class lets you record messages about the program's actions or errors.
private static final Logger logger = LoggerFactory.getLogger(ClassName.class);ClassName with the name of your current class.MyService class.private static final Logger logger = LoggerFactory.getLogger(MyService.class);logger.info("Starting process...");logger.error("An error occurred", exception);This Spring Boot service class creates a logger. It logs when the process starts and ends. It also catches and logs an error when dividing by zero.
package com.example.demo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; @Service public class MyService { private static final Logger logger = LoggerFactory.getLogger(MyService.class); public void runProcess() { logger.info("Process started"); try { int result = 10 / 0; // This will cause an error } catch (ArithmeticException e) { logger.error("Error during process", e); } logger.info("Process ended"); } }
Use logger.info() for normal messages, logger.error() for errors.
Logger messages help you understand what your app is doing without stopping it.
Logger helps track app behavior and errors.
Create a logger with LoggerFactory.getLogger(ClassName.class).
Use logger methods like info and error to write messages.
MyService?private static final Logger logger = LoggerFactory.getLogger(App.class);
public void run() {
logger.info("Start running");
logger.debug("Debugging info");
logger.error("An error occurred");
}OrderService:private Logger logger = LoggerFactory.getLogger(OrderService);
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?Pass the test and this pattern moves unknown