How to Change Logging Levels Dynamically in Spring Boot: A Complete Guide

Master Dynamic Log Level Management in Spring Boot Using Actuator and Custom APIs. Learn more about Spring Boot on BeingCoders.9 min


How-to-Change-Logging-Levels-Dynamically-in-Spring-Boot

# How to Change Logging Levels Dynamically in a Spring Boot Application

Logging is an essential part of any Spring Boot application. It helps in debugging, monitoring, and troubleshooting issues efficiently. However, setting a fixed log level in application.properties may not always be ideal. What if you need to change the logging level dynamically at runtime without restarting your application?

In this article, we will explore different ways to achieve this, including using Spring Boot Actuator and creating a custom REST API endpoint for changing log levels. By the end of this guide, you will have a clear understanding of how to modify logging levels dynamically in a Spring Boot application.

Dynamic Log level changes

This article will answer your below questions:

  • How to change log level dynamically in Spring Boot
  • Spring Boot Actuator log level change at runtime
  • Best practices for managing logging in Spring Boot applications
  • Secure API for modifying log levels dynamically in Spring Boot
  • Spring Boot logging configuration for production and debugging

Why Change Log Levels Dynamically?

  1. Efficient Debugging – Enable DEBUG or TRACE logging only when needed.
  2. Performance Optimization – Avoid excessive logging that may slow down the application.
  3. Production Monitoring – Adjust log levels dynamically in a live environment without restarting the server.
  4. Security & Compliance – Modify logging settings to capture only necessary information without exposing sensitive data.

Method 1. Changing Log Levels Using Spring Boot Actuator

Spring Boot Actuator provides a built-in way to modify logging levels dynamically through the /actuator/loggers endpoint.

Step 1: Add Spring Boot Actuator Dependency

To use Actuator, add the following dependency in your pom.xml (for Maven users):

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

For Gradle users, add:

implementation 'org.springframework.boot:spring-boot-starter-actuator'

Step 2: Enable Loggers Endpoint in Application Properties

By default, the /actuator/loggers endpoint is disabled. You need to enable it in application.properties:

management.endpoints.web.exposure.include=loggers

Alternatively, for application.yml:

management:
  endpoints:
    web:
      exposure:
        include: loggers

Step 3: Use Actuator to Modify Log Levels

Now, you can dynamically change the logging level by making an API call:

Check Current Logging Level

GET /actuator/loggers

This returns a list of all loggers and their current levels.

Modify Log Level

To change the logging level dynamically, use a POST request:

POST /actuator/loggers/com.example.demo
Content-Type: application/json
{
"configuredLevel": "DEBUG"
}

This will set the logging level of com.example.demo to DEBUG at runtime.

Step 4: Secure the Actuator Endpoint (Optional but Recommended)

Exposing the /actuator/loggers endpoint without security can be risky. You can secure it using Spring Security by modifying application.properties:

management.endpoints.web.exposure.include=loggers
management.endpoint.loggers.enabled=true
management.security.enabled=true

This ensures that only authenticated users can modify log levels.


Method 2: Creating a Custom REST API for Log Level Modification

If you don’t want to use Actuator, you can create a custom REST API to dynamically change log levels.

Step 1: Create a Controller for Log Level Changes

import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import org.springframework.http.ResponseEntity;

@RestController
@RequestMapping("/logs")
public class LogLevelController {
    @PostMapping("/{loggerName}/{level}")
    public ResponseEntity<String> changeLogLevel(@PathVariable String loggerName, @PathVariable String level) {
        Logger logger = (Logger) LoggerFactory.getLogger(loggerName);
        Level newLevel = Level.toLevel(level.toUpperCase(), Level.INFO);
        logger.setLevel(newLevel);
        return ResponseEntity.ok("Log level changed for " + loggerName + " to " + newLevel);
    }
}

Step 2: Use the Custom API to Change Log Levels

To modify the log level dynamically, make the following API request:

POST /logs/com.example.demo/DEBUG

This will set the logging level of com.example.demo to DEBUG.


Comparison: Actuator vs. Custom API

Feature Spring Boot Actuator Custom API
Ease of Use ✅ Yes ❌ Requires manual implementation
Security ✅ Can be secured via Spring Security ❌ Needs custom security handling
Flexibility ✅ Supports all loggers ✅ Fully customizable

Best Practices for Managing Logging Levels

  1. Use INFO or WARN in production – Avoid using DEBUG or TRACE logs unless necessary.
  2. Secure the logging endpoint — Unauthorized users should not modify log levels.
  3. Log rotation — Prevent log files from growing indefinitely.
  4. Use structured logging — Tools like ELK Stack (Elasticsearch, Logstash, and Kibana) help in better log analysis.
  5. Monitor logs in real-time — Use cloud-based log management tools like AWS CloudWatch or Datadog.

Conclusion

Changing logging levels dynamically in a Spring Boot application provides flexibility in debugging and monitoring.

  1. Spring Boot Actuator is the easiest and most secure way to manage logging levels.
  2. A custom REST API provides more flexibility if Actuator is not an option.
  3. Always follow best practices to ensure logging security and efficiency.

By implementing these techniques, you can optimize your logging strategy for better performance and debugging in production environments. 🚀


FAQs

1. Can I change the root logging level dynamically?
Yes, using Actuator: POST /actuator/loggers/root with { "configuredLevel": "INFO" }.

2. Does changing the logging level persist after a restart?
No, changes are runtime only. To persist changes, update application.properties.

3. Can I modify the logging levels of third-party libraries?
Yes, specify the package name, e.g., org.springframework instead of com.example.demo.

By following this guide, you can effectively manage logging levels in your Spring Boot application dynamically, ensuring optimal performance and troubleshooting capabilities. Happy coding! 🎯

adsense


Discover more from 9Mood

Subscribe to get the latest posts sent to your email.


Like it? Share with your friends!

What's Your Reaction?

Lol Lol
0
Lol
WTF WTF
0
WTF
Cute Cute
0
Cute
Love Love
0
Love
Vomit Vomit
0
Vomit
Cry Cry
0
Cry
Wow Wow
0
Wow
Fail Fail
0
Fail
Angry Angry
0
Angry
Rakshit Shah

Legend

Hey Moodies, Kem chho ? - Majama? (Yeah, You guessed Right! I am from Gujarat, India) 25, Computer Engineer, Foodie, Gamer, Coder and may be a Traveller . > If I can’t, who else will? < You can reach out me by “Rakshitshah94” on 9MOodQuoraMediumGithubInstagramsnapchattwitter, Even you can also google it to see me. I am everywhere, But I am not God. Feel free to text me.

0 Comments

Leave a Reply

Choose A Format
Story
Formatted Text with Embeds and Visuals
List
The Classic Internet Listicles
Ranked List
Upvote or downvote to decide the best list item
Open List
Submit your own item and vote up for the best submission
Countdown
The Classic Internet Countdowns
Meme
Upload your own images to make custom memes
Poll
Voting to make decisions or determine opinions
Trivia quiz
Series of questions with right and wrong answers that intends to check knowledge
Personality quiz
Series of questions that intends to reveal something about the personality
is avocado good for breakfast? Sustainability Tips for Living Green Daily Photos Taken At Right Moment