0
0
Spring Bootframework~5 mins

Logger creation in classes in Spring Boot

Choose your learning style9 modes available
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.

You want to track when a method starts and ends.
You need to record errors or warnings in your application.
You want to debug by printing useful information without stopping the program.
You want to keep a history of important events in your app.
You want to monitor how your app behaves in different environments.
Syntax
Spring Boot
private static final Logger logger = LoggerFactory.getLogger(ClassName.class);
Replace ClassName with the name of your current class.
This line creates a logger that you can use to write messages.
Examples
This creates a logger for the MyService class.
Spring Boot
private static final Logger logger = LoggerFactory.getLogger(MyService.class);
This logs an informational message.
Spring Boot
logger.info("Starting process...");
This logs an error message with an exception.
Spring Boot
logger.error("An error occurred", exception);
Sample Program

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.

Spring Boot
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");
    }
}
OutputSuccess
Important Notes

Use logger.info() for normal messages, logger.error() for errors.

Logger messages help you understand what your app is doing without stopping it.

Summary

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.