I am successfully using Spring's @Scheduled annotation to execute a method every few seconds. The only issue is that I get a lot of log messages about transactions, etc from Hibernate and Spring because of this method.
I want to keep the logging levels the same because I like to receive this information for other transactions in the application.
Is there a way in logback to temporarily suppress another library's logging while a specific method is executing?
Logback does not allow logging to be disabled from the command line. However, if the configuration file allows it, you can set the level of loggers on the command line via a Java system property.
To disable this behavior, you must add a logback configuration file called logback. xml in your java classpath root. You can download this minimal logback. xml file and add it in the src/main/resources directory for a maven project or beside fr directory for a simple java project.
Key Difference Between Log4j vs LogbackAs logback is improved, version log4j and versions log4j2 and logback have no difference in terms of performance or any features. Therefore log4j is the most used logging utility before the logback newer versions were invented.
You need to use Filters and MDC (Mapped Diagnostic Context). This solution will only affect the logging that occurs on the thread that is executing the @Scheduled
method.
@Scheduled
method, add an entry to the MDC of that thread.ch.qos.logback.core.filter.Filter<ILoggingEvent>
, which will return FilterReply.DENY
if that entry is set in the MDC<appender>
entry in logback.xml
Make your @Scheduled
method look like this:
@Scheduled(fixedRate=30000)
public void scheduledMethod () {
try{
MDC.put("scheduled", "true");
// Your code here
}finally{
MDC.remove("scheduled");
}
}
I should mention that removing the key is important because Spring may reuse the thread and the MDC would keep the value otherwise.
Your filter should look something like this:
package my.domain.application.logging;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.filter.Filter;
import ch.qos.logback.core.spi.FilterReply;
public class MDCFilter extends Filter<ILoggingEvent> {
@Override
public FilterReply decide(ILoggingEvent event) {
String scheduled = event.getMDCPropertyMap().get("scheduled");
if ("true".equals(scheduled)) {
return FilterReply.DENY;
} else {
return FilterReply.NEUTRAL;
}
}
}
Add the following to your logback.xml
<appender name="myAppender" class="ch.qos.logback.core.ConsoleAppender">
<filter class="my.domain.application.logging.MDCFilter" />
<!-- the rest of your appender -->
</appender>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With