I need to be able to print in production to logger, but while developing i would like to print to the console. So in c++ i would simply use a macro for it, and that would be a change of 1 line, how can i do that in java? Thanks
Macros aren't the right answer, using a good logging framework is. Look at SLF4J (or the older log4j). If you route all your logging calls through one of these facades, you'll be able to send your logged messages to the console, or a file, or any other appender that you like with a tiny bit of config.
Java doesn't have C/C++-like macros, and so there's no easy way to automatically disable all of your logging code. What you can do is something like this:
public class Utility {
private Utility() {} // Singleton
public static void log(String toLog) {
System.out.println(toLog);
}
/* ... etc. ... */
}
Now, anywhere in your program that you want to log an event, you can just call
Utility.log("Here's a message!");
In production builds, you can silence this output by just changing the implementation of log
to be a no-op.
This is not as efficient as the C/C++-ism of just having your logging macro expand to nothingness at compile-time, but a good optimizer/JIT should be able to notice that the argument isn't getting used and optimize away the logic to set up those arguments.
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