Bird
Raised Fist0
Spring Bootframework~10 mins

Logger creation in classes in Spring Boot - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Logger creation in classes
Start Class
↓
Declare Logger
↓
Initialize Logger with LoggerFactory
↓
Use Logger in Methods
↓
Log Messages at Different Levels
↓
End Class
This flow shows how a logger is declared, initialized, and used inside a Spring Boot class to log messages.
Execution Sample
Spring Boot
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MyService {
  private static final Logger logger = LoggerFactory.getLogger(MyService.class);

  public void doWork() {
    logger.info("Work started");
  }
}
This code creates a logger in a Spring Boot class and logs an info message inside a method.
Execution Table
StepActionEvaluationResult
1Class MyService loadedClass loadedReady to declare logger
2Declare logger variableprivate static final Logger loggerLogger variable declared but not initialized
3Initialize logger with LoggerFactory.getLogger(MyService.class)LoggerFactory creates logger instanceLogger instance assigned to logger variable
4Call doWork() methodMethod invokedInside method body
5Execute logger.info("Work started")Log message at INFO levelMessage sent to logging system
6Method doWork() endsNo return valueMethod completes
7Class usage endsNo further actionsProgram continues or ends
💡 Logging completes after method execution; no more code to run in this example.
Variable Tracker
VariableStartAfter InitializationAfter Method CallFinal
loggernullLogger instance for MyServiceLogger instance for MyServiceLogger instance for MyService
Key Moments - 3 Insights
Why do we use LoggerFactory.getLogger(MyService.class) instead of creating Logger directly?
LoggerFactory.getLogger(MyService.class) creates a logger tied to the class name, which helps identify log messages' source. This is shown in execution_table step 3 where the logger instance is created.
Why is the logger declared as static and final?
Declaring logger as static means one shared instance per class, and final means it cannot be reassigned. This is important for efficiency and consistency, as seen in execution_table step 2.
What happens when logger.info() is called inside the method?
The log message is sent to the logging system at INFO level, which can be seen in execution_table step 5 where the message is processed.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the state of the logger variable after step 3?
AIt holds a Logger instance for MyService
BIt holds a String message
CIt is null
DIt is uninitialized
💡 Hint
Check the 'Result' column in step 3 of the execution_table.
At which step does the log message "Work started" get sent to the logging system?
AStep 3
BStep 5
CStep 2
DStep 6
💡 Hint
Look for the step where logger.info() is executed in the execution_table.
If the logger was not declared static, what would change in the variable_tracker?
ALogger would remain null
BLogger would be shared across all classes
CLogger would be initialized multiple times per instance
DLogger would be a local variable
💡 Hint
Consider how static affects variable initialization shown in variable_tracker.
Concept Snapshot
Logger creation in Spring Boot classes:
- Declare logger as private static final
- Initialize with LoggerFactory.getLogger(ClassName.class)
- Use logger methods (info, debug, error) inside class methods
- Static ensures one logger per class
- Logger helps track runtime events clearly
Full Transcript
In Spring Boot, to create a logger inside a class, you declare a private static final Logger variable. You initialize it using LoggerFactory.getLogger with the class name. This ties the logger to the class, making log messages easy to identify. Inside your methods, you call logger methods like info() to send messages to the logging system. The static keyword means only one logger instance exists per class, improving efficiency. This process helps track what your application is doing while it runs.

Practice

(1/5)
1. What is the main purpose of creating a logger in a Spring Boot class?
easy
A. To record messages about the program's behavior for debugging and monitoring
B. To store user data permanently
C. To speed up the program execution
D. To create user interface elements automatically

Solution

  1. Step 1: Understand the role of a logger

    A logger records messages about what happens inside the program, helping developers see the flow and errors.
  2. Step 2: Identify the correct purpose

    Logging is not for storing data, speeding up code, or UI creation, but for tracking program behavior.
  3. Final Answer:

    To record messages about the program's behavior for debugging and monitoring -> Option A
  4. Quick Check:

    Logger purpose = record messages [OK]
Hint: Loggers track program events and errors clearly [OK]
Common Mistakes:
  • Thinking loggers store data permanently
  • Confusing loggers with UI components
  • Assuming loggers improve speed
2. Which of the following is the correct way to create a logger in a Spring Boot class named MyService?
easy
A. private Logger logger = LoggerFactory.createLogger(MyService);
B. Logger logger = new Logger(MyService);
C. private static final Logger logger = LoggerFactory.getLogger(MyService.class);
D. static Logger logger = LoggerFactory.getLogger("MyService");

Solution

  1. Step 1: Recall the standard logger creation syntax

    In Spring Boot, the logger is created using LoggerFactory.getLogger(ClassName.class) and declared static final.
  2. Step 2: Match the correct syntax

    private static final Logger logger = LoggerFactory.getLogger(MyService.class); matches the correct pattern: private static final Logger logger = LoggerFactory.getLogger(MyService.class); others use wrong methods or missing keywords.
  3. Final Answer:

    private static final Logger logger = LoggerFactory.getLogger(MyService.class); -> Option C
  4. Quick Check:

    Logger creation = LoggerFactory.getLogger(ClassName.class) [OK]
Hint: Use LoggerFactory.getLogger(ClassName.class) with static final [OK]
Common Mistakes:
  • Using new Logger() instead of LoggerFactory
  • Missing static or final keywords
  • Passing string instead of ClassName.class
3. Given the following code snippet in a Spring Boot class:
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");
}

What will be the visible output if the logging level is set to INFO?
medium
A. All three messages will be logged
B. No messages will be logged
C. Only "Debugging info" will be logged
D. Only "Start running" and "An error occurred" messages will be logged

Solution

  1. Step 1: Understand logging levels and filtering

    Logging levels filter messages: INFO level shows INFO, WARN, ERROR but hides DEBUG messages.
  2. Step 2: Apply level filter to messages

    "Start running" is INFO, "Debugging info" is DEBUG (hidden), "An error occurred" is ERROR (shown).
  3. Final Answer:

    Only "Start running" and "An error occurred" messages will be logged -> Option D
  4. Quick Check:

    INFO level hides DEBUG but shows INFO and ERROR [OK]
Hint: INFO level shows INFO and above, hides DEBUG [OK]
Common Mistakes:
  • Assuming DEBUG messages show at INFO level
  • Thinking ERROR messages are hidden
  • Confusing log levels order
4. Identify the error in the following logger declaration inside a Spring Boot class named OrderService:
private Logger logger = LoggerFactory.getLogger(OrderService);
medium
A. Logger must be declared inside a method, not as a field
B. Missing .class after OrderService in getLogger method
C. LoggerFactory does not have getLogger method
D. Logger should not be private

Solution

  1. Step 1: Check the getLogger argument type

    The getLogger method requires a Class object, so it should be OrderService.class, not OrderService.
  2. Step 2: Verify other parts of declaration

    Logger can be private and declared as a field; LoggerFactory has getLogger method; no need to declare inside method.
  3. Final Answer:

    Missing .class after OrderService in getLogger method -> Option B
  4. Quick Check:

    Use ClassName.class in getLogger [OK]
Hint: Always add .class after class name in getLogger() [OK]
Common Mistakes:
  • Omitting .class after class name
  • Thinking logger cannot be private
  • Assuming getLogger method doesn't exist
5. 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?
hard
A. 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"); } }
B. Logger logger = LoggerFactory.getLogger(UserController); public void checkUser(String userId) { if (userId == null) { logger.error("User ID is missing"); } }
C. private Logger logger = LoggerFactory.getLogger(UserController.class); public void checkUser(String userId) { if (userId.isEmpty()) { logger.info("User ID is missing"); } }
D. static final Logger logger = LoggerFactory.getLogger("UserController"); public void checkUser(String userId) { if (userId == null) { logger.debug("User ID is missing"); } }

Solution

  1. 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.
  2. 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.
  3. 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
  4. Quick Check:

    Use static final logger and logger.warn() for warnings [OK]
Hint: 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
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard