A template to create log4j Logger objects in Eclipse

In my (server) Java apps, I usually use log4j to keep logs. These days, I actually use SLF4J as a proxy for log4j, mostly because the framework I’m using (Vert.x) uses it.

Over the years I’ve tuned my log format to only store the information I care about, and nothing more than that:

<PatternLayout pattern="[%d{HH:mm:ss.SSS}] %p %c{3} - %m%n" />

so I have a timestamp, the log level (%p), the class name with up to 3 levels of package hierarchy (%c{3}), and the new-line-terminated message (%m%n).

A sample line:

[11:39:36.667] TRACE redis.redis_client.RedisDecoder - received new MultiBulkReply

This format requires a Logger object in all classes that need logging, which requires quite a bit of boilerplate code, e.g.:

private static final Logger LOGGER = LoggerFactory
    .getLogger(SlackRouter.class);

You quickly grow tired of typing all of that. But worry not! Eclipse comes to the rescue!

Setup an Eclipse Template

I created a template that does the work for me: now, all I have to do to add a new Logger object is type log, hit Ctrl + space, and select “Insert logger”.

Just like this:

Adding a Logger

Note that typing “log4” instead of “log” only gives you one option, saving 2 precious key strokes! 😛

Here’s how to set it up for your Eclipse.

  1. Open your Eclipse Preferences menu
  2. Type “java editor templates” in the search bar
    uno
  3. Hit the “New” button
  4. Set “log4j” as name (or whatever you want the shortcut to be), add a description, paste this in the “Pattern” field:
    ${:import(org.slf4j.Logger,org.slf4j.LoggerFactory)}
    private static final Logger LOGGER = LoggerFactory.getLogger(${enclosing_type}.class);
    

    and hit “OK”
    tre

  5. That’s it!

    If you’re not using SLF4J, all you need to do is change the import code to include the actual class you use.

Leave a comment