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?
- Understand the three main logging components
- Understand logging levels
- SLF4J: the logging facade
- Use SLF4J in a Spring Boot application
- Use Log4j2 instead of the default Logback
- 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>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout
pattern="%d{yyyy-MM-dd HH:mm:ss} %-5level %c - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="info">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>
Let's understand it.
Configuration
<Configuration status="WARN">
This is the main configuration element.
Appenders
<Appenders>
This section defines where log events should go.
We created a console appender:
<Console name="Console" target="SYSTEM_OUT">
PatternLayout
<PatternLayout
pattern="%d{yyyy-MM-dd HH:mm:ss} %-5level %c - %msg%n"/>
This defines how the log message should look.
Loggers
<Loggers>
This section defines logger configurations.
Root logger
<Root level="info">
The root logger acts as the parent logger for application loggers that don't have a more specific configuration.
We connected it to the console appender:
<AppenderRef ref="Console"/>
Now log messages at INFO level and above can be printed on the console.
Example:
2026-11-26 10:15:20 INFO com.example.UserService - User registered
2026-11-26 10:15:21 WARN com.example.UserService - Cache unavailable
2026-11-26 10:15:22 ERROR com.example.UserService - Database failed
Example: console and rolling file appenders
Let's make the configuration a little more practical.
We want:
- INFO and above messages on the console.
- DEBUG and above messages in a file.
- Automatic file rotation.
Example:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout
pattern="%d{yyyy-MM-dd HH:mm:ss} %-5level %c - %msg%n"/>
</Console>
<RollingFile
name="File"
fileName="logs/application.log"
filePattern="logs/application-%d{yyyy-MM-dd}-%i.log.gz">
<PatternLayout
pattern="%d{yyyy-MM-dd HH:mm:ss} %-5level %c - %msg%n"/>
<Policies>
<SizeBasedTriggeringPolicy size="10 MB"/>
</Policies>
<DefaultRolloverStrategy max="10"/>
</RollingFile>
</Appenders>
<Loggers>
<Root level="info">
<AppenderRef ref="Console"/>
<AppenderRef
ref="File"
level="debug"/>
</Root>
</Loggers>
</Configuration>
Here we created two appenders.
Console appender
<Console name="Console" target="SYSTEM_OUT">
Writes log messages to the console.
Rolling file appender
<RollingFile
name="File"
fileName="logs/application.log"
filePattern="logs/application-%d{yyyy-MM-dd}-%i.log.gz">
Writes logs to application.log and defines a naming pattern for archived files.
Size-based policy
<SizeBasedTriggeringPolicy size="10 MB"/>
When the file reaches the configured size, Log4j2 can roll over the file.
Maximum archives
<DefaultRolloverStrategy max="10"/>
Configures the maximum number of rollover files for this strategy.
The exact rollover behavior depends on the configured policies and strategy.
Appender reference
<AppenderRef ref="Console"/>
<AppenderRef ref="File" level="debug"/>
We connect both appenders to the root logger.
This means a DEBUG event can be sent to the file appender, while the console appender only receives events at its configured INFO threshold.
This is useful when you want more detailed information in files without flooding the console.
Database and email appenders
We discussed JDBCAppender and SMTPAppender earlier.
Let's understand where they fit.
JDBCAppender
A JDBCAppender can write log events into a database.
Conceptually:
Logger
|
v
JDBCAppender
|
v
Database connection
|
v
INSERT INTO application_logs ...
You need to configure:
- JDBC connection details.
- A connection source.
- A table.
- An appropriate SQL statement.
- The layout or message mapping required by the configuration.
For example, a log table might contain:
+--------------------------------------+
| application_logs |
+--------------------------------------+
| id |
| log_level |
| logger_name |
| message |
| created_at |
+--------------------------------------+
But remember: database logging is not automatically the best option.
A busy application can generate thousands of log events. Writing each event to the main application database can create additional load.
For many production systems, logs are written to files or standard output and then collected by a centralized logging platform.
SMTPAppender
An SMTPAppender can send log events through an SMTP server.
Conceptually:
Logger
|
v
SMTPAppender
|
v
SMTP Server
|
v
Email notification
For example, you may configure selected ERROR events to trigger email notifications.
This requires suitable mail dependencies and SMTP configuration.
Avoid sending an email for every log message. It can create excessive notifications and make important failures harder to notice.
Logging best practices
Before finishing, let's look at some practices worth following in real projects.
1. Use meaningful messages
Avoid:
logger.info("Here");
Prefer:
logger.info("User registration completed");
A useful log message should explain what happened.
2. Use the correct logging level
Don't log every message using ERROR.
For example:
logger.info("User logged in");
logger.warn("Payment retry limit is almost reached");
logger.error("Payment processing failed");
3. Use parameterized logging
Avoid unnecessary string concatenation:
logger.debug("User ID: " + userId);
Prefer:
logger.debug("User ID: {}", userId);
Parameterized logging can avoid unnecessary message construction when the level is disabled.
4. Never log sensitive information
Avoid logging:
- Passwords.
- Access tokens.
- Refresh tokens.
- API keys.
- Database credentials.
- Sensitive personal information.
Logs can be accessible to more people and systems than the application database itself.
5. Include exceptions when useful
Avoid:
logger.error("Something failed");
Prefer:
logger.error("Failed to save user", exception);
This allows the logging framework to record exception details and stack traces.
6. Avoid excessive logging
Logging every variable and every method call at INFO level makes production logs difficult to understand.
Use DEBUG or TRACE for detailed diagnostic information.
7. Configure log rotation
A log file that grows indefinitely can consume all available disk space.
Use a suitable rolling policy and retention period.
8. Use structured logging when needed
For distributed applications, JSON logs can be easier for centralized logging systems to parse and search.
9. Use correlation IDs
When a request passes through multiple services, a correlation ID helps you connect related log events.
For example:
Request ID: req-123
API Gateway -> req-123
User Service -> req-123
Payment Service -> req-123
This makes debugging distributed applications much easier.
Which one should I use?
Let's connect everything.
SLF4J
Use it as the logging API in your application code.
It keeps your code independent of the underlying logging implementation.
Logback
A common default choice in Spring Boot applications.
You generally don't need to replace it unless you have a specific requirement.
Log4j2
Choose it when you need its features, configuration capabilities, or when your organization standardizes on it.
ConsoleAppender
Useful for local development and container environments where standard output is collected by the platform.
FileAppender / RollingFileAppender
Useful when you need local log files and controlled file rotation.
JDBCAppender
Useful for selected scenarios where writing log events to a relational database is required.
SMTPAppender
Useful for selected email notifications, usually for serious events rather than routine logging.
For a typical Spring Boot application, a sensible starting point is:
Application Code
|
v
SLF4J
|
v
Logback
|
+----------+
| |
v v
Console File
If your project requires Log4j2, you can replace Logback with Log4j2 while keeping SLF4J in your application code.
Common mistakes
Using System.out.println() for application logging: It does not provide the same level filtering, destination management, and configuration capabilities as a logging framework. Use a logger instead.
Confusing SLF4J with Log4j2: SLF4J is a logging facade, while Log4j2 is a logging implementation and framework. Understand their different responsibilities.
Using ERROR for every message: ERROR should represent an actual error condition. Use INFO for normal events, WARN for concerning situations, and DEBUG or TRACE for diagnostic details.
Expecting DEBUG messages at the default INFO level: DEBUG is below INFO, so it is filtered out. Configure the appropriate logger level in Spring Boot.
Assuming the Logger writes directly to a file: The logger creates log events, while appenders deliver them to destinations. Layouts format those events.
Logging passwords and tokens: Logs can expose sensitive information. Never record authentication credentials, access tokens, or secrets in plain text.
Quick recap
- Logging records important events that happen inside an application.
-
System.out.println()is not a replacement for a proper logging framework. - A log event contains information such as level, logger name, timestamp, message, and exception details.
- Log messages can be sent to console, files, databases, or email.
- Logger creates log events.
- Appender decides where log events are delivered.
- Layout decides how log events are formatted.
- Common appenders include ConsoleAppender, FileAppender, RollingFileAppender, JDBCAppender, and SMTPAppender.
- Logging levels include TRACE, DEBUG, INFO, WARN, ERROR, and FATAL.
- SLF4J is a logging facade.
- Log4j2 is a logging framework and implementation.
- Spring Boot uses Logback by default with its standard logging starter.
- You can enable DEBUG logging using
logging.levelproperties. - You can configure file output using
logging.file.name. - You can replace the default Logback implementation with Log4j2 using
spring-boot-starter-log4j2. -
log4j2-spring.xmlis used for advanced Log4j2 configuration in Spring Boot.
Try it yourself
Don't just read these concepts. Try them in a Spring Boot project.
Practice 1: Create a Logger
Create a UserService class.
Create a logger using LoggerFactory.
Print messages using:
trace()debug()info()warn()error()
Observe which messages appear with the default logging level.
Practice 2: Enable DEBUG logging
Add this to application.properties:
logging.level.com.example=DEBUG
Run your application again.
Observe the difference.
Practice 3: Write logs to a file
Add:
logging.file.name=logs/application.log
Run your application and check whether the log file is created.
Practice 4: Understand Log4j2 components
Create a log4j2-spring.xml configuration.
Configure:
- One ConsoleAppender.
- One RollingFileAppender.
- One PatternLayout.
- One Root logger.
Generate log messages and observe where they appear.
Bonus challenge
Create a small Spring Boot application with a user registration endpoint.
Log these events:
INFO - Registration request received
DEBUG - Validating username
INFO - Username validation completed
INFO - Saving user
ERROR - Registration failed
Configure the application so that:
- INFO and above messages appear on the console.
- DEBUG and above messages are written to a file.
- Log files rotate when they reach 10 MB.
If this helped, or if you spotted something I should fix, tell me in the comments. I'm still learning too.
Top comments (0)