Slf4j / logback - different loglevel for specific threads

I recently changed our application from log4j to logback / slf4j. Everything works very well, however I want to implement something specific.

The application I'm working on is a web application. In our production environment, the log level is at INFO. From time to time, tickets are sent to our service team. It would be nice that when our service team plays tickets, they can put the log level on TRACE only for their test request. Thus, the log files will not vote for all other requests included at this time.

We already use the header "X-TracingContext-Active = true" to write some additional data to the log. My idea was to extend loglevel to TRACE when the title is "true" for this request (stream) only.

Is there a way to do this without having to create my own logging implementation or write this logic in each class?

EDIT: The X-TracingActive-Context header is now fixed at the beginning of each request. This value is stored in a helper class in the ThreadLocal variable. I was thinking of overriding the methods isInfoEnabled, isDebugEnabled, ... so it first reads the variable from the helper class. But I have no idea how I can override this method without implementing my own log structure. The Logger class is final.

Any ideas?

+4
source share
2 answers

Although you are not quite what you want (and not trivial to implement), you can set the level for TRACE for everything and filter out the “wrong” threads. Performance may / will be pretty terrible, though, but if you again log the log level only for the duration of these special requests and reset, it should not be so bad.

+1
source

The double's answer made me think. I already tried the log filtering mechanism, but that was not enough. There are apparently 2 types of filters in logback: Filter and TurboFilter. The latter was the solution to my problem.

In logback.xml, I configured TurboFilter:

<!-- Turbo Filters -->
<turboFilter class="com.company.application.core.util.LoggingTurboFilter" />

Class LoggingTurboFilter:

import org.slf4j.Marker;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.turbo.TurboFilter;
import ch.qos.logback.core.spi.FilterReply;

public class LoggingTurboFilter extends TurboFilter {

    @Override
    public FilterReply decide(Marker marker, Logger logger, Level level,
            String format, Object[] params, Throwable t) {

        if (!isStarted()) {
            return FilterReply.NEUTRAL;
        }

        if(CurrentLogLevelProvider.getTraceActive()){
            return FilterReply.ACCEPT;
        } else {
            return FilterReply.NEUTRAL;
        }
    }

    @Override
    public void start() {
        super.start();
    }
}

.

+1

All Articles