SLF4JCodeTemplate

Overview

Logging is a very useful mechanism for tracing problems that occur after you've deployed an application. The code for including a logger is standard boiler plate and can be quickly added using NetBeans Code Templates.

SLF4J

The use of logging facades is quite common in Java. Facades allow the developer to abstract away the specific logger implementation while developing and then plug-in the most appropriate implementation at runtime. (Such as Log4j, JDK Logging, etc.). For example, many Apache projects use commons-logging. Unfortunatly, commons-logging can give developers headaches; slf4j was introduced in order to avoid some of the issues with commons-logging.

From http://www.slf4j.org:

The Simple Logging Facade for Java or (SLF4J) is intended to serve as a simple facade for various logging APIs allowing to the end-user to plug in the desired implementation at deployment time. SLF4J also allows for a gradual migration path away from Jakarta Commons Logging (JCL).

Adding the Code Template

To add a logging code template in NetBeans do the following:

  1. Open the Options'" Dialog (Mac: Netbeans->Preferences, Other OS's: Tools->Options)
  2. Select the Editor button at the top of the dialog
  3. Select the Code Templates tab
  4. Click the New button
  5. Enter slog in the New Code Template Dialog box
  6. In the Expanded Text area add the following:

private static final ${LOG_TYPE type="org.slf4j.Logger" default="Logger" editable=false} log = ${LOG_FACT type="org.slf4j.LoggerFactory" default="LoggerFactory" editable=false}.getLogger(${CLASS editable="false" currClassName}.class);

Using the Code Template

To use the code template while editing a Java class you simply type the following: slog followed by tab. This will insert the following code into your class:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

...

    private static final Logger log = LoggerFactory.getLogger(CLASS);

Alterative (non-static) Template

If you prefer to use a non-static logger, follow the directions above but use the following Code Template:

private final ${LOG_TYPE type="org.slf4j.Logger" default="Logger" editable=false} log = ${LOG_FACT type="org.slf4j.LoggerFactory" default="LoggerFactory" editable=false}.getLogger(getClass());

This will expand to:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

...

    private final Logger log = LoggerFactory.getLogger(getClass());
Not logged in. Log in, Register

By use of this website, you agree to the NetBeans Policies and Terms of Use. © 2012, Oracle Corporation and/or its affiliates. Sponsored by Oracle logo