How to Set Logging Level for a Specific Class or Package in Spring Boot
Configuring logging at a granular level is crucial for software development, especially when your application contains multiple layers with varying verbosity requirements. Spring Boot simplifies this task with its built-in support for configuring logging levels, allowing developers to adjust log outputs per class or package. This helps maintain clarity and control over logs, reducing noise from unrelated components while focusing on areas that require attention.
This guide will explain how to set logging levels for specific classes or packages in Spring Boot applications, along with practical examples and troubleshooting tips.
Understanding Logging Level Inheritance in Java
Logging level inheritance is a critical concept when configuring logs for specific packages or classes in Java-based applications. Loggers follow a hierarchical structure where child loggers inherit the configuration of parent loggers unless explicitly overridden.
For example, in a package-hierarchy context:
- Logger
com.example
is the parent ofcom.example.service
andcom.example.repository
. - If
com.example
is configured at theINFO
level, all child loggers will also useINFO
unless their levels are explicitly set (e.g., toDEBUG
orERROR
).
This inheritance ensures consistency and simplifies configuration. However, you can fine-tune logging verbosity at granular levels for specific packages or even classes.
Using application.properties
: A Simple Example
Spring Boot provides its default configuration via the application.properties
file. Setting a log level for a specific package is straightforward:
Example:
To set the logging level to DEBUG
for a custom package com.example
:
logging.level.com.example=DEBUG
This configuration enables detailed logging for every class under the com.example
package while adhering to the default logging level for all other packages.
You can also configure loggers for specific frameworks. For instance:
logging.level.org.springframework.web=INFO logging.level.org.hibernate.SQL=DEBUG
This adjusts the verbosity for the Spring Web package and SQL queries generated by Hibernate.
YAML Format Alternative
If you prefer working with YAML configuration, Spring Boot supports the same functionality via application.yml
. Here’s the equivalent configuration for setting specific logger levels:
logging: level: com.example: DEBUG org.springframework.web: INFO org.hibernate.SQL: DEBUG
The structure is intuitive and allows for hierarchical configuration, making YAML an excellent choice for projects that require visual clarity.
Common Use Cases for Per-Package Logging
Granular logging serves several purposes, depending on your application’s needs. Below are some common scenarios where per-package logging proves invaluable:
1. Enable DEBUG
Only for Your Repository
When troubleshooting or optimizing data operations, you might want verbose logs for your repository layer:
logging.level.com.example.repository=DEBUG
This ensures detailed diagnostics for database interactions while keeping the rest of the application logs minimal.
2. Silence Third-Party Libraries
Third-party libraries can often generate excessive or irrelevant logs. You can suppress them by configuring higher log levels:
logging.level.org.apache=ERROR logging.level.com.thirdparty.sdk=OFF
Here, the Apache libraries are limited to error logs, and the third-party SDK logs are completely silenced.
3. Focused Logging During Development
During development, you may enable TRACE
or DEBUG
for specific packages that require close inspection:
logging.level.com.example.service=TRACE
This approach isolates the service layer’s detailed trace logs for debugging complex flows.
Using logback.xml
for Fine Control
For advanced configurations, you can use Logback’s XML-based configuration file (logback-spring.xml
). This gives you more flexibility over log formatting, appenders, and rolling policies.
Example:
To set DEBUG
level logging for the com.example
package in logback-spring.xml
:
<configuration> <logger name="com.example" level="DEBUG" /> <logger name="org.hibernate" level="ERROR" /> <root level="INFO"> <appender-ref ref="CONSOLE" /> </root> </configuration>
The <logger>
element configures logging levels for specific packages or classes, while the <root>
logger defines the global settings.
Rolling File Logging for Specific Packages:
If you need to manage log outputs for specific packages in separate files:
<logger name="com.example" level="DEBUG" additivity="false"> <appender-ref ref="FILE" /> </logger>
This configuration isolates logs, ensuring that only messages from com.example
are written to the specified file.
Dynamic Runtime Change via Actuator
Spring Boot Actuator provides powerful tools for dynamically adjusting logging configurations at runtime without restarting the application.
Enable Actuator Logging Endpoint:
To access the /actuator/loggers
endpoint:
- Add Actuator to your project:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
- Expose the logging endpoint:
management.endpoints.web.exposure.include=loggers
Adjust Logging Level Dynamically:
Send a POST request to change the log level:
curl -X POST -H "Content-Type: application/json" \ -d '{"configuredLevel": "DEBUG"}' \ http://localhost:8080/actuator/loggers/com.example
The /actuator/loggers
endpoint also supports viewing current log levels and resetting them dynamically.
Testing Configurations with Known Log Points
After setting logging levels, verify the configuration by triggering known log points in your application. For example, intentionally call methods that generate logs to ensure the expected verbosity.
Example:
Trigger a repository query or make a test HTTP request to validate logs:
logger.debug("Fetching user details for user ID {}", userId);
Verify that the logged message matches the DEBUG
level settings applied.
Troubleshooting Logging Scope Issues
When log configurations do not behave as expected, try the following troubleshooting steps:
- Check Hierarchical Settings:
Ensure that the desired logging level isn’t being overridden by a parent logger.
- Validate Actuator Configuration:
Query the /actuator/loggers
endpoint to confirm the active log levels for your package/class.
- Inspect Configuration Overrides:
If using both application.properties
and logback-spring.xml
, ensure the log settings are consistent across files.
Logging Format Per Package (Optional)
Customizing the log format for specific packages is possible with Logback appenders. For example:
<appender name="CustomAppender" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{35} - %msg%n</pattern> </encoder> </appender> <logger name="com.example" level="DEBUG"> <appender-ref ref="CustomAppender" /> </logger>
This allows you to standardize or create custom log outputs for isolated components.
Final Thoughts
Setting logging levels for specific classes or packages in Spring Boot gives developers precise control over the volume and relevance of log output. Whether you’re silencing noisy libraries, isolating verbose debug logs to a single package, or integrating advanced logging tools like Actuator, these techniques ensure efficient and insightful logging in your applications. By following these configurations and best practices, you can optimize logs for better performance, traceability, and troubleshooting.