SLF4J - logging regardless of log level

In my Java application, I am using SLF4J + Logback for logging. I use DEBUG logging in development and ERROR in production. But there are some messages that I want to be logged anyway, regardless of the log level (similar System.out.println("Some Message")

, but using the log).

Is there any practical way to achieve this? I can use bugs or lower levels, but what I want to do is provide some information, so logger.error("Some message");

is semantically incorrect, this is not a bug.

I can define a different log in mine logback.xml

for my class / classes, but that is not convenient.

What is the correct way to achieve this?

+3


source to share


1 answer


This is where the great "Marker" SLF4J / Logback function comes in handy. Suppose you want to log into the console all warnings / errors, as well as anything that has a special "Status" message.

You can have a class for logging like this:

public class MyClass {
    private static final Marker status = MarkerFactory.getMarker("STATUS");
    private static final Logger logger = LoggerFactory.getLogger(MyClass.class);

    public void doSomething() {
        logger.info(status, "Beginning");
        logger.info("Regular info log");
        logger.warn("Warning");
        logger.info(status, "Done");
    }
}

      



Then in the logback.xml you filter to display all warnings and messages marked "STATUS":

<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
    <filter class="ch.qos.logback.core.filter.EvaluatorFilter">
        <evaluator class="ch.qos.logback.classic.boolex.OnMarkerEvaluator">
            <marker>STATUS</marker>
        </evaluator>
        <OnMatch>ACCEPT</OnMatch>
        <OnMismatch>NEUTRAL</OnMismatch>
    </filter>
    <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
        <level>WARN</level>
    </filter>
    <encoder>
        <pattern>${pattern}</pattern>
    </encoder>
</appender>

      

Basically, you have a DEBUG logger level, so everything goes to the app, and then in the appender does some more filtering to get the exact lines you are looking for. If you're trying to use more different levels of logging for different classes, it can get a little tricky, but Logback gives you a lot of flexibility with filters (and you can even create your own filters if needed), which allows you to handle pretty much everything you need.

+1


source







All Articles