Getting Started With SLF4J (Java Logging Façade)

SLF4J is a next-generation logging façade API for Java. SLF4J supplants the older Apache Commons Logging.

You write your code to call SLF4J’s logging commands. Those commands are actually just an empty interface. You plug in a particular logging framework to actually record messages. You can plug in an adapter to work with Java's built-in but limited logging facility. Or you can plug in an adapter to add an insulating layer to the venerable but aging log4j already in use by your projects. Or for a greenfield project, drop in Logback to do your logging. Logback is the successor to log4j, created by the same man.

Alternatively, just to get started, you can use the SimpleLogger implementation of the SLF4J API. SimpleLogger simply dumps messages to the Standard Error console (stderr or System.err in Java terms) console. This is handy during development. Later you can drop in a more serious logging framework such as Logback. Those other framework may require more configuration, coordination with your sysadmins, so you may want to defer that until later.

SimpleLogger has a few options. You may tweak those merely by setting Java System Properties. I like to switch SimpleLogger from using System.err to System.out because Eclipse has a known nasty bug where lines from those two streams can be improperly mixed on console pane with lines appearing out of order. I also tell SimpleLogger to show me all levels of messages rather than ignoring the lower-level ones. Lastly I add the datetime and shorten the class name to hide the package name.

Here's my code called at the launch of my app, or for web apps, the initialization of the servlet.

// Logging
// 5 levels: "trace", "debug", "info", "warn", or "error".
// For now, we use the "SimpleLogger" implementation.
// But let's tweak "Simple" to use System.out rather than System.err because Eclipse has a bug interleaving the two
// out of order.
// And let's override "Simple" default of ignoring lower-level messages to track all levels of messages.
// We communicate with "Simple" via System Property settings (key-value pairs).
// Doc: http://www.slf4j.org/api/org/slf4j/impl/SimpleLogger.html
System.setProperty( "org.slf4j.simpleLogger.logFile", "System.out" );
System.setProperty( "org.slf4j.simpleLogger.defaultLogLevel", "trace" );
System.setProperty( "org.slf4j.simpleLogger.showShortLogName", "true" );
System.setProperty( "org.slf4j.simpleLogger.showDateTime", "true" );
SimpleDateFormat simpleDateFormat = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss.SZ" );
System.setProperty( "org.slf4j.simpleLogger.dateTimeFormat", simpleDateFormat.toPattern() );

// Above is the setup needed to run at the beginning of your app.
// Next two lines are what you use in the various classes to actually do logging.
this.logger = LoggerFactory.getLogger( this.getClass() );
logger.info( "Hello World from slf4j." );

1 comment: