Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable logging in Java at compile time

I have some Java code that I'd like to instrument with log messages for debugging purposes. The final (compiled) production code, however, should not contain any logging as it would slow down the execution time. Is there any way in Java to disable a logger at compile time?

I am not afraid of the footprint a check inside the log method of a run-time enabled/disabled logger would add.

if (logging==enabled) {// do logging}

But I'd like to avoid parameter construction like the following in my production code:

Logger.log("undefined state" + state + " @ " + new Date());

I am using Sun's Java Compiler.

like image 469
Max Avatar asked Jun 22 '10 09:06

Max


2 Answers

Have you considered the slf4j approach with {}-placeholders. That allows for delayed construction of the toString() meaning that log.debug(...) is cheap if debug logging is disabled.

log.debug("in loop() - a={}, b={}", a, b);
like image 199
Thorbjørn Ravn Andersen Avatar answered Sep 22 '22 02:09

Thorbjørn Ravn Andersen


if(logger.isDebugEnabled()) {
  logger.debug(expression);
}

Every logging framework I've used requires you to use the above pattern to avoid unnecessary evaluation of the logging expression.

like image 29
McDowell Avatar answered Sep 21 '22 02:09

McDowell