Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java logging do not execute info when level is severe

Tags:

java

logging

I'm using java.util.logging

I have a foo function:

public String foo() {
    System.out.println("syso ==> foo");
    return "foo";
}

When I change the log level I don't wan't foo to be executed!

Logger logger = Logger.getLogger(MyClass.class.getSimpleName());
FileHandler fileHandler = new FileHandler("myapp.log");
logger.addHandler(fileHandler);
logger.setLevel(Level.SEVERE);
logger.info("Write foo: " + foo() );
logger.severe("Test severe");

I know that the logger.info() won't be printed in the log file, but why to execute foo()? How can I solve it?

Thank's

like image 459
user80042 Avatar asked Jan 30 '26 00:01

user80042


2 Answers

Though it doesn't display that text, the line does get executed, because that line is not a comment.

If using Apache Logger, then try using Logger.isInfoEnabled() method this way:-

if(logger.isInfoEnabled()){
    logger.info("Write foo: " + foo() );
}

Else, if its jdk logger, then use the below method as suggested by @n1ckolas

if (logger.isLoggable(Level.INFO)) {
    logger.info("Write foo: " + foo() );
}
like image 165
Rahul Avatar answered Feb 01 '26 14:02

Rahul


The fact that you disable info does not make the logger.info line "invisible" to the compiler and linker. This line is still going to execute and since you make a call to foo it will be executed as well.

You should use the Logger methods to check if info level is enabled and only than use log.info

If you are using apache logger than use :

if (logger.isInfoEnabled()) {
    logger.info("Write foo: " + foo() );
}
like image 20
giorashc Avatar answered Feb 01 '26 13:02

giorashc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!