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
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() );
}
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() );
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With