user3133542
user3133542

Reputation: 1715

Log4J2: Substituting Parameters does not work properly

Im using Log4J 2.8.2.

The manual (https://logging.apache.org/log4j/2.0/manual/api.html) says that substituting Parameters is better done with placeholders:

That means

logger.debug("Logging in user {} with birthday {}", user.getName(), user.getBirthdayCalendar());

is better than

if (logger.isDebugEnabled()) {
    logger.debug("Logging in user " + user.getName() + " with birthday " + user.getBirthdayCalendar());
}

because:

the logging level will only be checked once and the String construction will only occur when debug logging is enabled.

So lets say I have following two methods:

public static String getSentence() {
        System.out.println("Sentence Invoked!");
        return "{} im the Best!";
    }

    public static String expensiveOperation() {
        System.out.println("Expensive Invoked!");
        return "John Doe";
    }

Now the Level of the rootLogger is set to INFO. If I log the following way:

LOGGER.debug(getSentence(), expensiveOperation());

I get following output:

Sentence Invoked!
Expensive Invoked!

That means both methods are invoked, although there is no logging happening because LOGGER's Level is DEBUG and rootLoggers's Level is INFO.

I would have expected that neither of the methods getSentence() and expensiveOperation() would be invoked. Have I done something wrong?

Upvotes: 0

Views: 402

Answers (1)

MANOJ
MANOJ

Reputation: 736

Logs are filtered based on the log levels set (Handler will only receive the filtered logs). but jvm does executes every logs.

Upvotes: 1

Related Questions