Imagine you are building a Spring Boot application.
Everything works perfectly on your machine. You register users, authenticate them, save data to the database, and return responses.
But one day, something goes wrong in production.
A user reports that registration is failing. Another user says the application is responding slowly. You check the application, but you have no idea what happened when those requests were processed.
How would you investigate?
You could add System.out.println() statements everywhere:
System.out.println("User registration started"); System.out.println("Checking username"); System.out.println("Saving user"); System.out.println("Registration completed"); This might work for a small program, but it becomes difficult to manage in a real application.
You need something better.
You need a way to record application events, understand what happened, identify errors, and investigate problems even after they occur.
This is where logging comes in.
In this blog, we'll understand logging from scratch, explore its components, learn about logging levels, and finally configure SLF4J and Log4j2 in a Spring Boot application.
Table of contents
- Start with the problem: why do we need logging?
- Why System.out.println() is not enough
- What is a log message?
- Where can log messages go?
- Understand the three main logging components
- What is a Logger?
- Create a Logger in Java
- What is an Appender?
- Common appenders
- What is a Layout?
- How the components work together
- Understand logging levels
- TRACE
- DEBUG
- INFO
- WARN
- ERROR
- FATAL and OFF
- SLF4J: the logging facade
- Why do we need SLF4J?
- SLF4J vs Log4j2
- How SLF4J and Log4j2 work together
- Use SLF4J in a Spring Boot application
- Enable debug logging in Spring Boot
- Configure logging in application.properties
- Write logs to a file
- Use Log4j2 instead of the default Logback
- Configure Log4j2 with log4j2-spring.xml
- Example: console and rolling file appenders
- Database and email appenders
- Logging best practices
- Which one should I use?
- Common mistakes
- Quick recap
- Try it yourself
Start with the problem: why do we need logging?
Let's start with a simple example.
Suppose we have a user registration method:
public void registerUser(User user) { // Validate user // Save user // Return response } Now imagine the registration fails.
Where did it fail?
- Did username validation fail?
- Did the database connection fail?
- Did saving the user fail?
- Was there an unexpected exception?
Without useful records of what happened, debugging becomes difficult.
Logging solves this problem by recording important events that happen while your application is running.
For example:
2026-11-26 10:00:01 INFO User registration started 2026-11-26 10:00:02 INFO Username validation completed 2026-11-26 10:00:03 INFO User saved successfully 2026-11-26 10:00:03 INFO User registration completed Now we have a timeline of what happened.
If something fails, we can inspect the logs and understand where the problem occurred.
Why System.out.println() is not enough
You might be thinking:
"Why do we need a logging framework? Can't we just use System.out.println()?"
Let's compare them.
1. No logging levels
With System.out.println(), every message is just printed.
You cannot naturally distinguish between:
- Normal application information.
- Debugging information.
- Warnings.
- Errors.
You can manually add labels, but you would still need to build the filtering and configuration mechanisms yourself.
2. Difficult to control output
Suppose you want to print debugging messages only during development.
With System.out.println(), you may have to search for and remove or comment out many statements.
With a logging framework, you can configure the logging level without changing your logging statements.
3. No built-in destination management
You may want logs to go to:
- Console.
- Files.
- A database.
- A remote logging system.
A logging framework provides configurable destinations through appenders.
4. Difficult to maintain
A real application can contain hundreds of classes.
A proper logging framework gives you a consistent way to create, filter, format, and manage log messages.
So, instead of:
System.out.println("User registered"); We can write:
logger.info("User registered"); Much cleaner.
What is a log message?
A log message is a record of an event that happened inside an application.
For example:
INFO User registered successfully WARN Password reset link is about to expire ERROR Database connection failed A log event can contain more than just the message.
It may contain:
- Timestamp.
- Logging level.
- Logger name.
- Thread name.
- Message.
- Exception information.
- Additional context.
For example:
2026-11-26 10:15:20 ERROR com.example.service.UserService User registration failed The logging framework collects this information and sends it to the configured destination.
One important distinction:
A successful operation is not a separate logging level.
For example:
logger.info("User registered successfully"); A warning is also not necessarily a failed operation:
logger.warn("Password reset link is about to expire"); And a failure is commonly recorded using:
logger.error("User registration failed"); The level tells us the severity or importance of the event. The message explains what happened.
Where can log messages go?
Once an application creates a log message, where should it be stored?
There are several possibilities.
1. Console
The log message is printed in the terminal or IDE console.
Example:
INFO User registered successfully This is useful during local development because you can immediately see what your application is doing.
2. File
The log message is written to a file, commonly with a .log extension.
Example:
logs/application.log This is useful when you need to inspect application activity after it has happened.
3. Database
The log message is inserted into a database table.
For example:
+--------------------------------------+ | application_logs | +--------------------------------------+ | id | level | message | time | +--------------------------------------+ | 1 | INFO | User created | 10:00 | | 2 | ERROR | DB failed | 10:05 | +--------------------------------------+ This can be useful in specific systems where logs need to be queried using application-specific database operations.
However, storing every application log in your main database is not always a good idea. It can create unnecessary database load and complicate retention.
4. Email
Some logging configurations can send notifications through SMTP.
For example, you may configure an email appender to send an email when a serious error occurs.
ERROR: Payment processing failed Application: Payment Service Time: 10:15 AM This can be useful for selected critical events, but sending an email for every log message would quickly become noisy.
Understand the three main logging components
Now let's understand how a logging framework manages these operations.
Three important components are:
- Logger
- Appender
- Layout
Think of them like a newspaper publishing process.
- Logger: Decides which event needs to be recorded.
- Appender: Decides where the record should go.
- Layout: Decides how the record should look.
Let's understand them one by one.
What is a Logger?
A logger is the object through which your application creates log messages.
Whenever a class needs to write logs, it obtains a logger and uses it.
For example:
logger.info("User registered"); logger.warn("Invalid request received"); logger.error("Database connection failed"); The logger is the entry point of the logging process.
It also has a name, which is commonly the fully qualified name of the class that created it.
For example:
com.example.service.UserService Why is the logger name useful?
Imagine you have 100 classes in your application.
You may want to enable DEBUG logs only for:
com.example.service.UserService You don't necessarily want debugging messages from every other class.
Logger names and package hierarchies make this possible.
Create a Logger in Java
Let's create a simple Java class using SLF4J.
import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class UserService { private static final Logger logger = LoggerFactory.getLogger(UserService.class); public void registerUser() { logger.info("User registration started"); logger.debug("Validating username"); logger.info("User registered successfully"); } } Let's understand the important line:
private static final Logger logger = LoggerFactory.getLogger(UserService.class); Logger
Logger This is the logging interface provided by SLF4J.
LoggerFactory
LoggerFactory It is responsible for providing a logger instance.
UserService.class
UserService.class This tells the factory which class is requesting the logger.
The resulting logger is associated with the UserService class name.
Why static final?
-
static: One logger reference is shared by instances of the class. -
final: The reference cannot be reassigned.
You can use this logger throughout the class.
What is an Appender?
We have created a logger and written:
logger.info("User registered successfully"); But where does this message go?
Does the logger itself write directly to the console?
Not necessarily.
This is where an Appender comes in.
An appender decides where a log event should be delivered.
For example:
Logger | v Appender | v Console Or:
Logger | v Appender | v application.log You can configure multiple appenders for a logger.
For example, the same log event can be sent to both the console and a file.
Common appenders
Let's understand some common Log4j2 appenders.
1. ConsoleAppender
Writes log messages to the console.
Logger | v ConsoleAppender | v Terminal Useful during local development.
2. FileAppender
Writes log messages to a file.
Logger | v FileAppender | v application.log Useful when you want to preserve log output.
3. RollingFileAppender
Writes logs to a file and can rotate the file when configured size or time conditions are met.
For example:
logs/ application.log application-2026-11-25.log application-2026-11-24.log This prevents one log file from growing indefinitely.
4. JDBCAppender
Writes log events to a relational database using JDBC.
For example:
Logger | v JDBCAppender | v Database | v application_logs table You need to configure the database connection and the SQL statement used to insert log events.
5. SMTPAppender
Can send log events through email using SMTP.
For example, you could configure it to send an email for ERROR-level events.
Important: These are different destinations supported by logging implementations. You do not need to configure every appender in every application.
What is a Layout?
We now know:
- Logger creates log events.
- Appender sends them to a destination.
But how should the message look?
For example, should it look like this?
INFO User registered Or this?
2026-11-26 10:15:20 INFO com.example.service.UserService User registered This is where a Layout comes in.
A layout controls how a log event is formatted before it is written by an appender.
For example, a Pattern Layout lets you define a pattern.
%d %-5level %c - %msg%n Let's understand the pattern:
-
%d: Date and time. -
%-5level: Logging level, aligned to five characters. -
%c: Logger name. -
%msg: Log message. -
%n: New line.
Example output:
2026-11-26 10:15:20 INFO com.example.UserService - User registered You can also use different layouts.
For example:
- Pattern Layout: Human-readable text.
- JSON Template Layout: Structured JSON.
- XML Layout: XML-formatted output.
JSON logs are especially useful when logs are collected by centralized logging platforms because machines can parse the fields easily.
How the components work together
Now let's connect everything.
Suppose your code executes:
logger.error("Payment processing failed"); What happens?
+----------------------------+ | Logger | | | | logger.error(message) | +----------------------------+ | v +----------------------------+ | Appender | | | | Decide destination | +----------------------------+ | v +----------------------------+ | Layout | | | | Format the log event | +----------------------------+ | v +----------------------------+ | Destination | | | | Console / File / DB / SMTP | +----------------------------+ The exact internal pipeline can include filters, logger configurations, and other components. But this is the basic mental model.
Remember:
- Logger: Who creates the log event?
- Appender: Where should the event go?
- Layout: How should the event be formatted?
Understand logging levels
Not every event in an application has the same importance.
For example:
Application started User logged in Cache miss occurred Database connection failed Should all these messages have the same priority?
No.
Logging frameworks provide different logging levels to classify messages based on their severity.
The common Log4j2 levels, ordered from least severe to most severe, are:
TRACE | v DEBUG | v INFO | v WARN | v ERROR | v FATAL OFF is used to disable logging.
Let's understand each level.
TRACE
TRACE is used for very detailed information about application execution.
For example:
logger.trace("Entering validateUser() method"); logger.trace("Checking username length"); logger.trace("Exiting validateUser() method"); When would you use it?
Suppose a method contains multiple conditions and you need to understand exactly which path the application follows.
TRACE can help you inspect those details.
It is usually too detailed for normal production logging.
DEBUG
DEBUG is used for information that helps developers investigate application behavior.
Example:
logger.debug("User ID received: {}", userId); logger.debug("Fetched {} records from database", users.size()); You might use DEBUG when:
- Investigating an issue.
- Understanding a method's execution.
- Checking intermediate values.
- Debugging a database query or service call.
It is commonly enabled during development or temporarily when troubleshooting production issues.
Be careful not to log passwords, tokens, or other sensitive values.
INFO
INFO is used for normal application events.
For example:
logger.info("Application started"); logger.info("User registered successfully"); logger.info("Payment processed successfully"); These messages help you understand the application's normal operation.
For many applications, INFO is a reasonable default logging level.
WARN
WARN is used when something unexpected happens, but the application can still continue.
Example:
logger.warn("Password reset link is about to expire"); logger.warn("Cache is unavailable, falling back to database"); A warning does not always mean that an operation failed.
It tells us that something deserves attention.
ERROR
ERROR is used when an operation fails or an important problem occurs.
Example:
logger.error("Database connection failed"); You can also log an exception with its stack trace:
try { userRepository.save(user); } catch (Exception exception) { logger.error("Failed to save user", exception); } The exception object allows the logging framework to include useful diagnostic information, such as the exception type and stack trace.
Don't swallow exceptions just because you logged them. Your application still needs to handle or propagate the failure appropriately.
FATAL and OFF
FATAL
Log4j2 provides a FATAL level for very severe events that may cause the application to stop working.
Example:
logger.fatal("Application cannot initialize critical configuration"); However, not all logging frameworks support FATAL.
For example, SLF4J's standard Logger API does not expose a fatal() method. In SLF4J applications, such events are commonly logged using error().
OFF
OFF disables logging at the configured level.
For example, a logger configured with OFF will not emit normal log events.
Now, how does a logging level actually work?
Suppose we configure:
Root logging level: INFO The logger accepts messages at INFO and more severe levels.
So:
TRACE -> Not logged DEBUG -> Not logged INFO -> Logged WARN -> Logged ERROR -> Logged Why?
Because INFO is the minimum severity that we want to record.
This is called the logging threshold.
SLF4J: the logging facade
Now let's discuss another name you will frequently see in Java applications: SLF4J.
SLF4J stands for Simple Logging Facade for Java.
It provides a common logging API that your application can use without depending directly on one particular logging implementation.
But why do we need another logging library when Log4j2 already exists?
Let's understand the problem.
Why do we need SLF4J?
Imagine you are developing an application using Log4j2.
Your code directly imports Log4j2 classes:
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; Now suppose your team decides to switch from Log4j2 to Logback.
You may need to change logging imports and code across multiple classes.
That creates unnecessary coupling between your application code and the logging implementation.
SLF4J solves this by providing a common API.
Instead of writing code directly against Log4j2, you write:
import org.slf4j.Logger; import org.slf4j.LoggerFactory; Your application uses SLF4J.
A compatible logging provider handles the actual logging.
This separates:
- The API used by application code.
- The implementation that performs logging.
SLF4J vs Log4j2
This is one of the most common points of confusion.
Are SLF4J and Log4j2 competitors?
Not exactly.
They serve different roles.
SLF4J
SLF4J is a logging facade.
It provides interfaces such as:
Logger LoggerFactory It defines how your application writes log messages.
It does not provide the complete logging implementation and configuration system by itself.
Log4j2
Log4j2 is a logging framework.
It provides the actual logging implementation through its API and Log4j Core.
It supports:
- Loggers.
- Appenders.
- Layouts.
- Logging levels.
- Filters.
- Configuration files.
A simple comparison:
+--------------------------------+ | SLF4J | | | | Common Logging API | +--------------------------------+ | v +--------------------------------+ | Logging Provider | | | | Log4j2 | +--------------------------------+ | v +--------------------------------+ | Log4j Core | | | | Loggers / Appenders / Layouts | +--------------------------------+ | v Console / File / DB You can use SLF4J with Log4j2.
You can also use SLF4J with other compatible logging implementations, such as Logback.
How SLF4J and Log4j2 work together
Let's see the actual code.
import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class PaymentService { private static final Logger logger = LoggerFactory.getLogger(PaymentService.class); public void processPayment() { logger.info("Payment processing started"); logger.debug("Validating payment details"); logger.info("Payment processed successfully"); } } Notice that we imported:
org.slf4j.Logger org.slf4j.LoggerFactory We did not import Log4j2 classes.
If Log4j2 is configured as the SLF4J provider, these calls are handled by Log4j2.
If Logback is configured as the provider, the same SLF4J logging code can work with Logback.
This is the main benefit of SLF4J.
Your application code remains independent of the underlying logging implementation.
Use SLF4J in a Spring Boot application
Now let's move to Spring Boot.
Suppose you create a Spring Boot application using the standard starters.
Do you need to manually install a logging framework?
Usually, no.
Spring Boot provides logging support automatically through its starter dependencies.
By default, Spring Boot uses Logback when the standard logging starter is present.
This means you can start using SLF4J directly.
For example:
package com.example.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; @Service public class UserService { private static final Logger logger = LoggerFactory.getLogger(UserService.class); public void registerUser() { logger.info("User registration started"); logger.debug("Validating user details"); logger.info("User registered successfully"); } } You don't need to manually configure a logger for every class in an XML file.
The logger can be obtained using LoggerFactory.
Enable debug logging in Spring Boot
Suppose your application contains:
logger.debug("Validating user details"); But you don't see the message in the console.
Why?
Because Spring Boot's default logging level is INFO.
DEBUG messages are below the INFO threshold, so they are filtered out.
How do we enable them?
There are multiple ways.
Option 1: Enable debug mode when starting the application
java -jar myapp.jar --debug You can also use:
debug=true But be careful.
Spring Boot's debug mode enables additional DEBUG-level output for selected core loggers. It does not enable DEBUG logging for every logger in your application.
Option 2: Enable DEBUG for your application package
In application.properties:
logging.level.com.example=DEBUG Now DEBUG messages from loggers under com.example can be recorded.
Option 3: Enable DEBUG for one class
logging.level.com.example.service.UserService=DEBUG This is useful when you are investigating one specific class.
Option 4: Enable DEBUG globally
logging.level.root=DEBUG This enables DEBUG logging for the root logger and can produce a lot of output, including messages from framework libraries.
Use it carefully.
Configure logging in application.properties
Spring Boot provides convenient logging properties.
Let's look at some common configurations.
Set the root logging level
logging.level.root=INFO Enable DEBUG for your application
logging.level.com.example=DEBUG Enable TRACE for a specific package
logging.level.com.example.service=TRACE Reduce Spring Web logs
logging.level.org.springframework.web=WARN Enable SQL logging
For Hibernate SQL statements, you can configure:
logging.level.org.hibernate.SQL=DEBUG To inspect SQL parameter binding, the exact logger depends on the Hibernate version. For Hibernate 6, a commonly used logger is:
logging.level.org.hibernate.orm.jdbc.bind=TRACE Be careful with SQL parameter logging in production because it can expose sensitive data.
Write logs to a file
By default, Spring Boot logs to the console.
What if we also want a file?
We can configure:
logging.file.name=logs/application.log Now Spring Boot writes logs to:
logs/ application.log You can also specify a directory:
logging.file.path=logs When only the path is configured, Spring Boot uses the default file name spring.log.
If both logging.file.name and logging.file.path are configured, the file name property takes precedence.
Spring Boot also supports log file rotation through the underlying logging system.
For standard Logback configurations, you can customize rotation properties using logging.logback.rollingpolicy.*.
For more advanced configuration, use the native configuration file of your selected logging implementation.
Use Log4j2 instead of the default Logback
Now let's say you specifically want to use Log4j2 in your Spring Boot application.
Remember:
Spring Boot uses Logback by default when the standard logging starter is present.
To switch to Log4j2, we need to replace the default logging implementation.
Configure Log4j2 with log4j2-spring.xml
If you use Maven, exclude the default logging starter and add the Log4j2 starter.
For example, if you are using spring-boot-starter-web, configure it like this:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j2</artifactId> </dependency> Make sure you use the Spring Boot dependency management or parent POM so that the dependency versions remain compatible.
You should also check that another dependency has not brought the default logging implementation back onto the classpath.
Why do we exclude spring-boot-starter-logging?
Because that starter brings the default Logback-based logging setup.
We want Log4j2 to be the actual logging implementation.
Once configured, create this file:
src/ main/ resources/ log4j2-spring.xml Why log4j2-spring.xml instead of log4j2.xml?
Spring Boot provides additional Log4j2 configuration extensions.
The -spring variant allows those extensions to be used during configuration.
Configure Log4j2 with log4j2-spring.xml
Let's create a basic configuration.
<?xml version="1.0" encoding="UTF-8"?> <Configuration status="WARN"> <Appenders> <Cons...