Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to implement macros in java

Tags:

java

macros

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

like image 419
Sophie Avatar asked Mar 20 '11 09:03

Sophie


2 Answers

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.

like image 99
GaryF Avatar answered Sep 28 '22 17:09

GaryF


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.

like image 21
templatetypedef Avatar answered Sep 28 '22 16:09

templatetypedef