Use Lombok’s @CustomLog for logging in Liferay


Lombok is a excellent Java library that helps to greatly reduce boilerplate code. If you do not know Lombok yet, check out their website and have a look at their detailed documentation which has many examples.

One neat feature of Lombok are the various @Log annotations, for example @Log4j2 to make the usage of Apache’s log4j 2 more easy:

@Log4j2
public class LogExample {
  
  public static void main(String... args) {
    log.info("Let us start!");
  }
}

Unfortunately, there is no @Log variant for Liferay’s log mechanism. However, with Lombok’s new @CustomLog (introduced in version 1.18.10) we can handle that in a pleasing manner.

First you need to make sure that you have a lombok.config file in your project’s root folder. Then add the following line to this file:

lombok.log.custom.declaration = com.liferay.portal.kernel.log.Log com.liferay.portal.kernel.log.LogFactoryUtil.getLog(TYPE)(TOPIC)

This will tell Lombok how to create a new Liferay log object. That is all you need to do, from now on you can use @CustomLog in your code like in this example here:

@CustomLog
public class LiferayLogExample {
  
  public static void main(String... args) {
    log.info("Go, go, go!");
  }
}

Compare that to the code full of boilerplate we had to write before:

import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
...
public class LiferayLogExample {
  private static Log log = LogFactoryUtil.getLog(LiferayLogExample.class);

  public static void main(String... args) {
    log.info("Go, go, go!");
  }
}