Quick Eclipse Tip

Whenever programming Java, it’s always a good idea to log what the program is doing. Log this error, log that object’s value – it’s a constant occurrence. More often than not, I’m adding this simple line to the fields of every class I write:

private final Log log = LogFactory.getLog(ThisClass.class);

Not only is this repetitive and time-consuming, it is easily automated in the form of a Template from within Eclipse.

The Solution

Adding a text expansion in the form of an Eclipse Template, allows for typing log, press the content assist hotkey, followed by pressing Enter, to automatically insert the Log declaration statement and add the necessary imports. Wow, that was fast, was my initial response. No way am I ever going to type that out manually again.

How to do it

In Eclipse, navigate to Window -> Preferences. In the tree on the left-hand side, go under Java -> Editor -> Templates. Here is the screen for defining text expansions that will be available when using the editor. Click New, enter “log” or whatever of your choosing as the name to expand from. Select the context drop-down to “Java type members”. Finally copy and paste the following into the Pattern field:

private final Log log = LogFactory.getLog(${enclosing_type}.class);
${imp:import(org.apache.commons.logging.Log, org.apache.commons.logging.LogFactory)}

Save it, apply changes, and exit the Preferences window. You are all good to go now!

Note

This assumes that you’re using Apache Commons Logging library for all of your logging tasks. The above template can easily be converted to define your specific logger of choice.

Published by

Jon Simpson

I’m a software engineering professional interested in Continuous Delivery, Lean, hipster programming languages, and distributed computing. In my spare time I enjoy reading books, tasting craft beers, and exploring Canada’s capital. I have a Bachelors of Computer Science with a specialization in Network Computing from Carleton University, Ottawa.

Leave a Reply

Your email address will not be published. Required fields are marked *