<p>Is it possible for the compiler to remove statements used for debugging purposes (such as logging) from production code? The debug statements would need to be marked somehow, maybe using annotations.</p>

<p>It's easy to set a property (debug = true) and check it at each debug statement, but this can reduce performance. It would be nice if the compiler would simply make the debug statements vanish.</p>

[{'answer_id': 32046, 'author': 'sparkes', 'author_id': 269, 'author_profile': 'https://Stackoverflow.com/users/269', 'pm_score': 0, 'selected': False, 'text': '<p>Use <a href="http://discuss.fogcreek.com/joelonsoftware/default.asp?cmd=show&amp;ixPost=63500" rel="nofollow noreferrer">Java Preprocessor</a>?  (google foo low but this is a link to the old Joel forums discussing it)</p>\n'}, {'answer_id': 32067, 'author': 'izb', 'author_id': 974, 'author_profile': 'https://Stackoverflow.com/users/974', 'pm_score': 3, 'selected': False, 'text': '<pre><code>public abstract class Config\n{\n    public static final boolean ENABLELOGGING = true;\n}\n</code></pre>\n\n<hr>\n\n<pre><code>import static Config.*;\n\npublic class MyClass\n{\n    public myMethod()\n    {\n        System.out.println("Hello, non-logging world");\n\n        if (ENABLELOGGING)\n        {\n            log("Hello, logging world.");\n        }\n    }\n}\n</code></pre>\n\n<p>The compiler will remove the code block with "Hello, logging world." in it if ENABLE_LOGGING is set to true because it\'s a static final value. If you use an obfuscator such as proguard, then the Config class will vanish too.</p>\n\n<p>An obfuscator would also allow things like this instead:</p>\n\n<pre><code>public class MyClass\n{\n    public myMethod()\n    {\n        System.out.println("Hello, non-logging world");\n\n        Log.log("Hello, logging world.");\n    }\n}\n</code></pre>\n\n<hr>\n\n<pre><code>import static Config.*;\n\npublic abstract class Log\n{\n    public static void log(String s)\n    {\n        if (ENABLELOGGING)\n        {\n            log(s);\n        }\n    }\n}\n</code></pre>\n\n<p>The method Log#log would reduce to nothing in the compiler, and be removed by the obfuscator, along with any calls to that method and eventually even the Log class would itself be removed.</p>\n'}, {'answer_id': 32077, 'author': 'Peter Stuifzand', 'author_id': 1633, 'author_profile': 'https://Stackoverflow.com/users/1633', 'pm_score': 0, 'selected': False, 'text': '<p>Java contains some sort of preprocessor of its own. It\'s called <a href="http://java.sun.com/j2se/1.5.0/docs/guide/apt/" rel="nofollow noreferrer">APT</a>. It processes and generates code. At the moment I\'m not sure how this should work (I haven\'t tried it). But it seems to be used for these kind of things.</p>\n'}, {'answer_id': 32091, 'author': 'cschol', 'author_id': 2386, 'author_profile': 'https://Stackoverflow.com/users/2386', 'pm_score': -1, 'selected': False, 'text': '<p>To directly answer your question: I don\'t know.</p>\n\n<p>But here is another solution to your problem:\nIn my mind, there are two statements that collide with each other here: "debug statements" and "production code". </p>\n\n<p>What is the purpose of debug statements? Help to get rid of bugs while (unit) testing. If a piece of software is properly tested and works according to the requirements, debug statements are nothing else but OBSOLETE.</p>\n\n<p>I strongly disagree with leaving any debug statements in production code. I bet nobody bothers testing side-effects of debug code in production code. The code probably does what it\'s supposed to do, but does it do more than that? Do all your #defines work correctly and really take ALL of the debug code out? Who analyzes 100000 lines of pre-processed code to see if all the debug stuff is gone?</p>\n\n<p>Unless we have a different definition of production code, you should consider taking out the debug statements after the code is tested and be done with it.</p>\n'}, {'answer_id': 32122, 'author': 'Mark Renouf', 'author_id': 758, 'author_profile': 'https://Stackoverflow.com/users/758', 'pm_score': 6, 'selected': True, 'text': '<p>Two recommendations.</p>\n\n<p><strong>First:</strong>\nfor real logging, use a modern logging package like log4j or java\'s own built in logging. Don\'t worry about performance so much, the logging level check is on the order of nanoseconds. (it\'s an integer comparison).</p>\n\n<p>And if you have more than a single log statement, guard the whole block:</p>\n\n<p>(log4j, for example:)</p>\n\n<pre><code>if (logger.isDebugEnabled()) {\n\n  // perform expensive operations\n  // build string to log\n\n  logger.debug("....");\n}\n</code></pre>\n\n<p>This gives you the added ability control logging at runtime. Having to restart and run a debug build can be very inconvenient.</p>\n\n<p><strong>Second:</strong></p>\n\n<p>You may find <a href="http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html" rel="noreferrer">assertions</a> are more what you need. An assertion is a statement which evaluates to a boolean result, with an optional message:</p>\n\n<pre><code> assert (sky.state != FALLING) : "The sky is falling!";\n</code></pre>\n\n<p>Whenever the assertion results in a false, the assertion fails and an AssertionError is thrown containing your message (this is an unchecked exception, intended to exit the application). </p>\n\n<p>The neat thing is, these are treated special by the JVM and can toggled at runtime down to the class level, using a VM parameter (no recompile needed). If not enabled, there is zero overhead.</p>\n'}, {'answer_id': 32342, 'author': 'HadleyHope', 'author_id': 3416, 'author_profile': 'https://Stackoverflow.com/users/3416', 'pm_score': 0, 'selected': False, 'text': '<p>I would also highly recommend using a logging framework.</p>\n\n<p>The <code>logger.IsDebugEnabled()</code> is not mandatory, it is just that it can be faster to check whether the system is in the debug level before logging.</p>\n\n<p>Using a logging framework means you can configure logging levels on the fly without restarting the application.</p>\n\n<p>You could have logging like:</p>\n\n<pre><code>logger.error("Something bad happened")\nlogger.debug("Something bad happend with loads more detail")\n</code></pre>\n'}, {'answer_id': 32484, 'author': 'Dana the Sane', 'author_id': 2567, 'author_profile': 'https://Stackoverflow.com/users/2567', 'pm_score': 1, 'selected': False, 'text': "<p>Another possibility is to put the if statement within your logging function, you get less code this way, but at the expense of some extra function calls.</p>\n\n<p>I'm also not a big fan of completely removing the debug code. Once you're in production, you'll probably need access to debug messages if something goes wrong. If you remove all of your code level debugging, than this isn't a possibility.</p>\n"}, {'answer_id': 23541646, 'author': 'Hiep', 'author_id': 347051, 'author_profile': 'https://Stackoverflow.com/users/347051', 'pm_score': 1, 'selected': False, 'text': '<p>This "<a href="http://lembra.wordpress.com/2010/07/27/remove-ifdebug-from-java-bytecode-with-a-static-flag/" rel="nofollow">trick</a>" seems to make your debug statements vanished</p>\n\n<pre><code>public static final boolean DEBUG = false;\n\nif (DEBUG) { //disapeared on compilation }\n</code></pre>\n\n<p>The <a href="http://lembra.wordpress.com/2010/07/27/remove-ifdebug-from-java-bytecode-with-a-static-flag/" rel="nofollow">post</a> said that <code>javac</code> is smart enough to check the <code>static final boolean</code> and exclude the debug statements. (I did not personally try it)</p>\n\n<p>For logging, I personally donot like to see code like:</p>\n\n<pre><code>if (logger.isDebugEnabled()) {\n    logger.debug("....");\n}\nrealImportantWork();\n</code></pre>\n\n<p>The logging things distracts me from the <code>realImportantWork()</code>. The right way for me is:</p>\n\n<pre><code>logger.debug("....");\nrealImportantWork()\n</code></pre>\n\n<p>plus the config which excludes all debug messages on Production.</p>\n\n<p>I mean that the <code>logger.isDebugEnabled()</code> control should be the job of the logging framework, not my job. Most logging framework support concepts like "logger", "LogLevel".. which can do the trick.</p>\n'}]
['https://Stackoverflow.com/questions/32041', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1772/']