Sunday, February 20, 2011

Tweaking Eclipse for LOG statements

Sometimes it’s good to revisit known/boring/old concepts! I just happened to read this article on Logging.

Particularly the section ‘Get your IDE to do the hard work’ caught my attention. Thought this'll add to my productivity in what ever little way!


I created these two little template xmls which you can import to your IDE. With this, we don’t need to write the same boiler plate code every time.

Advantages:

·         When I type in getlog and hit Ctrl+Space, Eclipse generates the following for me, with the proper class name filled:
private static final Log LOG = LogFactory.getLog(THE_CLASS_NAME.class);

·         When I type debug and hit Ctrl+Space, I get the complete if-block, and cursor placed inside the double quotes, ready to type the message.
if (LOG.isDebugEnabled()) {
    LOG.debug("msg");
}

·         When I type catch and hit Ctrl+Space, I get below:
catch (Exception e) {
    LOG.error("", e);
}
The same behavior also works if you use content assist for adding try catch block.

To get this, follow below simple instructions in your eclipse:
1.    Window -> Preferences -> Java -> Editor ->Templates
Click import, and import Java Editor Templates.xml
2.    Window -> Preferences -> Java -> Code Style -> Code Templates
Click import, and import Java Code Template.xml


Java Editor Templates:


<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
- <templates>
  <template autoinsert="false" context="java" deleted="false" description="catch block" enabled="true" id="org.eclipse.jdt.ui.templates.catch" name="catch">catch (${Exception} e) { LOG.error("${msg}", e); }</template>
  <template autoinsert="true" context="java" deleted="false" description="if (LOG.isDebugEnabled())" enabled="true" name="debug">if (LOG.isDebugEnabled()) { LOG.debug("${msg}"); }</template>
  <template autoinsert="true" context="java" deleted="false" description="Log LOG = LogFactory.getLog" enabled="true" name="getLog">${:import(org.apache.commons.logging.Log, org.apache.commons.logging.LogFactory)} private static final Log LOG = LogFactory.getLog(${enclosing_type}.class);</template>
  </templates>




Java Code Template:

  <?xml version="1.0" encoding="UTF-8" standalone="no" ?>
- <templates>
  <template autoinsert="false" context="catchblock_context" deleted="false" description="Code in new catch blocks" enabled="true" id="org.eclipse.jdt.ui.text.codetemplates.catchblock" name="catchblock">LOG.error("", ${exception_var});</template>
  </templates>

No comments:

Post a Comment