0% found this document useful (0 votes)
5 views12 pages

Spring Boot Logging Guide

The document provides an overview of logging in Spring Boot, explaining its importance for debugging, monitoring, and record-keeping. It details the implementation steps, default configurations, and how to customize logging settings using application.properties and logback-spring.xml. Additionally, it discusses the advantages and disadvantages of logging, as well as practical examples and common interview questions related to logging in Spring Boot applications.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views12 pages

Spring Boot Logging Guide

The document provides an overview of logging in Spring Boot, explaining its importance for debugging, monitoring, and record-keeping. It details the implementation steps, default configurations, and how to customize logging settings using application.properties and logback-spring.xml. Additionally, it discusses the advantages and disadvantages of logging, as well as practical examples and common interview questions related to logging in Spring Boot applications.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Logging in Spring Boot

What is Logging?
Logging means recording important information about what your application is doing
while it runs — like events, errors, or messages — to the console or a file.

Why do we need Logging?


We need logging to:

1.​ 🐞 Find and fix bugs — helps understand what went wrong.

2.​ 🧠 Monitor application behavior — see what your app is doing.

3.​ 📜 Keep records — store logs for audits or future reference.

4.​ ⚙ Debug in production — find issues without stopping the app.

1. Logging in Spring Boot


🔧 Implementation Steps:

Spring Boot uses Spring Boot Starter Logging, backed by Logback by default.

🔹 Basic Setup:

In [Link]:

# Set log level (OFF, ERROR, WARN, INFO, DEBUG, TRACE, ALL)
[Link]=INFO [Link]=DE

# File Logging [Link]=[Link]


[Link]=logs
🔹 Log Output Format (Optional):

[Link]=%d{yyyy-MM-dd HH:mm:ss} - %msg%n

Spring Boot includes logging by default:

When you add any starter like:

<dependency>

<groupId>[Link]</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

Spring Boot automatically includes:

<dependency>

<groupId>[Link]</groupId>

<artifactId>spring-boot-starter-logging</artifactId>

</dependency>
Example: Logging in a Spring Boot Controller

What is an Appender?
An Appender is a component in a logging framework (like Logback or Log4j) that decides
where your log messages go.

In Simple Words

An Appender tells the logger where to write the logs, such as:

●​ 🖥 Console

●​ 📁 File

●​ 📤 Database

●​ ☁ Remote server
What’s inside spring-boot-starter-logging?

It brings in:

●​ Logback (default backend)


●​ SLF4J (logging facade)

✅ What is the default logging in Spring Boot?

●​ Default Logging Framework: Logback

●​ Logging Facade: SLF4J (Simple Logging Facade for Java)

●​ Logging Starter: Included via spring-boot-starter-logging (auto-added)


📌 What is the default log level in Spring Boot?

●​ ✅ Default Log Level: INFO

●​ So by default, only logs at level INFO, WARN, and ERROR are shown.
DEBUG and TRACE messages are hidden unless explicitly enabled.

📌 To enable DEBUG or TRACE:

●​ In [Link]:

[Link]=DEBUG

✅ When you run a Spring Boot app, where can you see the logs?

●​ By default, Spring Boot logs are visible in the console (terminal/output window).

🗂 To write logs to a file (optional):

●​ Add this in [Link]:


●​ [Link]=[Link]

📁 Where is the file created?

➡ Location:
<your-project-root>/logs/[Link]

●​ [Link]=logs/ means a folder named logs will be created inside your


project directory

●​ [Link]=[Link] means the file will be named [Link]


📝 Example:

●​ If your project is at:


●​ C:\Users\Vijay\Projects\MySpringApp
●​
●​ Then the log file will be at:
●​ C:\Users\Vijay\Projects\MySpringApp\logs\[Link]


Important Notes:

●​ No need to create the logs folder manually — Spring Boot will auto-create it.

●​ If the app doesn't have write permission, the file won't be created.
🎯 Practical Example:
[Link]("Something failed");
[Link]("This might be an issue");
[Link]("Service started");
[Link]("Value of X = " + x);
[Link]("Entering method foo()");

●​ If level is set to INFO, only INFO, WARN, and ERROR logs will appear.
●​ If the level is set to DEBUG, you will see DEBUG, INFO, WARN, and ERROR
✅ Advantages:

●​ Easy configuration.

●​ Built-in support with profiles.

●​ File and console logging supported.

●​ Can change log level at runtime with actuator.

❌ Disadvantages:

●​ Verbose logs unless filtered.

●​ No log rotation by default (need config).

●​ No GUI for viewing logs.

💡 Log Monitoring Tools:

●​ Log4j2: Better performance.


●​ ELK Stack (ElasticSearch + Logstash + Kibana): For centralized log analysis.
●​ Sentry, Splunk, Datadog: For monitoring/log aggregation.
Importance interview question:

Q1: Where do we configure log appenders in Spring Boot (real-time


projects)?

Answer:
In real-time Spring Boot projects, we configure log appenders inside the
➡ [Link] file (placed in src/main/resources folder).

This file allows us to define how and where logs are stored — like console, file, or rolling files.

Q2: What is an Appender in logging?

Answer:
An Appender decides where the log messages will go, such as:

●​ Console (using ConsoleAppender)

●​ File (using FileAppender)

●​ Rolling files (using RollingFileAppender)

Q3: How do we define log format in real-time projects?

Answer:
We define the log message format inside the <encoder> tag in [Link].

<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss} %-5level [%thread] %logger{36} -
%msg%n</pattern>
</encoder>

This pattern controls how each log line looks (time, level, thread, class, message).
Q4: How do we implement log rolling (log rotation)?

Answer:
Log rolling (or rotation) is configured using RollingFileAppender with a
TimeBasedRollingPolicy.
It automatically creates new log files (daily or by size) and deletes old ones.

Example:

<rollingPolicy
class="[Link]">
<fileNamePattern>logs/app-%d{yyyy-MM-dd}.log</fileNamePattern>
<maxHistory>7</maxHistory>
</rollingPolicy>

●​ Creates a new log file every day

●​ Keeps only the last 7 days of logs

Q5: Why do we use RollingFileAppender in real-time projects?

Answer:
Because it:

●​ Prevents single log files from getting too large 🧹


●​ Automatically rotates logs daily or by file size 📅
●​ Helps in log management and troubleshooting 🧠
Q6: How do we configure a separate error log file ([Link]) in real-time
Spring Boot projects?

Answer:
In real-time projects, we often store error logs separately for easier debugging and production
monitoring.
This is done using a dedicated RollingFileAppender for errors in the
[Link] file.

🧾 Example Configuration
<appender name="ERROR_FILE"
class="[Link]">
<file>logs/[Link]</file>

<rollingPolicy
class="[Link]">

<fileNamePattern>logs/error-%d{yyyy-MM-dd}.log</fileNamePattern>
<maxHistory>10</maxHistory>
</rollingPolicy>

<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss} %-5level [%thread]
%logger{36} - %msg%n</pattern>
</encoder>

<!-- ✅Only capture ERROR level logs -->


<filter class="[Link]">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>

<!-- Attach this appender to the root logger -->


<root level="INFO">
<appender-ref ref="CONSOLE" />
<appender-ref ref="FILE" />
<appender-ref ref="ERROR_FILE" />
</root>
💡 How it Works

●​ All logs (INFO, WARN, ERROR) go to:

○​ Console
○​ Main [Link] file

●​ Only ERROR level logs are written to:

○​ [Link] file

So you’ll have two files in /logs:

●​ [Link] → all logs


●​ [Link] → only errors

THANK YOU AND FOLLOW ME FOR MORE

You might also like