This is a mobile version, full one is here.

Yegor Bugayenko
23 May 2014

Get Rid of Java Static Loggers

This is a very common practice in Java (using LoggerFactory from slf4j):

import org.slf4j.LoggerFactory;
public class Foo {
  private static final Logger LOGGER =
  public void save(String file) {
    // save the file
    if (Foo.LOGGER.isInfoEnabled()) {"file {} saved successfuly", file);

What’s wrong with it? Code duplication.

This static LOGGER property has to be declared in every class where logging is required. Just a few lines of code, but this is pure noise, as I see it.

To make life easier, I created a library about two years ago, jcabi-log, which has a convenient utility class Logger (yes, I know that utility classes are evil).

import com.jcabi.log.Logger;
public class Foo {
  public void save(String file) {
    // save the file, "file %s saved successfuly", file);

This looks much cleaner to me and does exactly the same—sends a single log line to the SLF4J logging facility. Besides, it check automatically whether a given logging level is enabled (for performance optimization) and formats the given string using Formatter (same as String.format()).

For convenience, there are also a number of “decors” implemented in the library.

The library ships as a JAR dependency in Maven Central (get its latest versions in Maven Central):