SLF4J and Logback help you add messages to your app that tell what is happening. This makes it easier to find problems and understand your app's behavior.
0
0
SLF4J and Logback basics in Spring Boot
Introduction
You want to see errors or warnings when your app runs.
You want to keep a record of important events in your app.
You want to control how much detail is shown in logs without changing code.
You want to send logs to different places like files or the console.
You want a simple way to add logging that works well with Spring Boot.
Syntax
Spring Boot
private static final Logger logger = LoggerFactory.getLogger(YourClass.class); logger.info("This is an info message"); logger.error("This is an error message");
Use LoggerFactory.getLogger() to create a logger for your class.
Use different methods like info(), error(), debug() to log messages with levels.
Examples
Logs an informational message when the app starts.
Spring Boot
private static final Logger logger = LoggerFactory.getLogger(MyApp.class); logger.info("App started successfully");
Logs an error message with details from an exception.
Spring Boot
logger.error("Failed to load data: {}", exception.getMessage());Logs debug information, useful during development but often turned off in production.
Spring Boot
logger.debug("User input: {}", userInput);Sample Program
This Spring Boot app uses SLF4J with Logback to log messages when the app starts and if it fails.
Spring Boot
package com.example.demo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { private static final Logger logger = LoggerFactory.getLogger(DemoApplication.class); public static void main(String[] args) { logger.info("Starting the Spring Boot application"); try { SpringApplication.run(DemoApplication.class, args); logger.info("Application started successfully"); } catch (Exception e) { logger.error("Application failed to start", e); } } }
OutputSuccess
Important Notes
Logback is the default logging framework used by Spring Boot when you use SLF4J.
You can configure Logback using logback-spring.xml or application.properties to change log levels and outputs.
Use placeholders like {} in log messages to insert variables safely.
Summary
SLF4J provides a simple way to write log messages in your code.
Logback is a powerful tool that handles how and where logs are saved or shown.
Using them together helps you understand what your app is doing and find problems faster.