Tarin Gamberini

A software engineer and a passionate java programmer

Code Templates For Logging

When I want to log a message, a variable, or an exception I would like to write it quickly. Therefore I’ve created some templates which generate logging instruction based on slf4j.

Netbeans IDE

I have created the following code template:

1
private static final ${LOGGER_TYPE type="org.slf4j.Logger" default="Logger" editable=false} LOGGER = ${LOGGER_FACTORY type="org.slf4j.LoggerFactory" default="LoggerFactory" editable=false}.getLogger(${CLASS editable="false" currClassName}.class);

and I have associated it to the abbreviation log. Than at the cursor:

1
2
3
public class MyClass {
    |
    ...

I type log + TAB and NetBeans expands the text:

1
2
3
4
5
6
7
8
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

...

public class MyClass {
    private static final Logger LOGGER = LoggerFactory.getLogger(MyClass.class);
    ...

I have also defined the shortcuts:

  • logd + TAB
  • logw + TAB
  • logi + TAB
  • loge + TAB

defined as:

  • ${LOGGER_CONST default="LOGGER" editable=false}.debug("${logMessage}");
  • ${LOGGER_CONST default="LOGGER" editable=false}.warn("${logMessage}");
  • ${LOGGER_CONST default="LOGGER" editable=false}.info("${logMessage}");
  • ${LOGGER_CONST default="LOGGER" editable=false}.error("${logMessage}", ex);

which generate:

1
2
3
4
LOGGER.debug("logMessage");
LOGGER.warn("logMessage");
LOGGER.info("logMessage");
LOGGER.error("logMessage", ex);

Eclipse IDE

Sometime I use Eclipse which has code templates too:

  • Windows > Preferences
  • Java > Editor > Templates
  • New

The log shortcut is defined as:

1
2
${:import(org.slf4j.Logger,org.slf4j.LoggerFactory)}
private static final ${loggerType:newType(org.slf4j.Logger)} LOGGER = ${loggerFactoryType:newType(org.slf4j.LoggerFactory)}.getLogger(${enclosing_type}.class);

while the the various:

  • logd
  • logw
  • logi
  • loge

are defined as:

  • LOGGER.debug(${word_selection}${});${cursor}
  • LOGGER.warn(${word_selection}${});${cursor}
  • LOGGER.info(${word_selection}${});${cursor}
  • LOGGER.error(${word_selection}${});${cursor}

Post a comment

A comment is submitted by an ordinary e-mail. Your e-mail address will not be published or broadcast.

This blog is moderated, therefore some comments might not be published. Comments are usually approved by the moderator in one/three days.