简体   繁体   中英

SLF4J - Logging regardless of the log level

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

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

I can define another logger in my logback.xml for my class/classes, but it is not convenient.

What is the right way to achieve this?

This is where the wonderful "Marker" feature of SLF4J/Logback comes in very handy. Say you want to log to the console all warnings/errors, as well as anything that's a special "Status" message.

You can have a class do 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 logback.xml, you filter to show 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 the logger's level be DEBUG so that everything goes to the appender, and then in the appender do further filtering to get the exact lines you're looking for. If you are trying to have more different logging levels for different classes it can get a bit trickier, but Logback gives a lot of flexibility with filters (and you can even make your own filters if needed) which lets one handle pretty much anything needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM