Compile debugging code to or from Java

I would like to be able to debug debugging code (verbose logging, etc.) when I create a production release, but compiled for debugging.

I understand that if I switch to a constant, the compiler will delete the branch that I want. So I have a class:

class Debug { public static final boolean ON=true; } 

and my debug code is inside the branch:

 if (Debug.ON) { // Verbose / expensive logging goes here } 

My question is: how can I set the Debug.ON parameter to true or false at compile time, and not actually edit the source file?

EDIT: Please note that I do not manage log output or not - I use java.util.Logging and it can take care of that. I'm more interested in compiling any expensive code that prepares log messages that will never be output, or measurements that are not needed in production mode.

I suppose I might have an ant target that makes the source file from a template or something like that, but it seems to be hacked. In C ++, I could define a preprocessor character that I could pass with -D - is there any Java equivalent? Or another better way?

0
java compilation
source share
2 answers

What you can do is have two Jars or class files.

One contains the Debug class with ON = true, and the other ON = false.

Then, when you compile, depending on what debug state you want, you include DEBUG in the class file / jar or the DEBUG file in class / jar.

+1
source share

Michael Wales answer is probably the easiest way to do exactly what you ask. However, all of the popular logging structures allow you to query whether a log is configured to actually output anything at a particular level of logging.

For java.util.logging you should use isLoggable . Although this is not a compilation time check, it should be fairly cheap compared to logging something expensive to compute.

0
source share

All Articles