Member-only story
SLF4J Resource Bundles & Lombok: A Practical Guide to Localized Logging in Java
Enable internationalization in SLF4J with resource bundles & Lombok. Simplify logging with a unified interface & localized messages.
SLF4J (Simple Logging Facade for Java) is a unified logging interface that abstracts various logging frameworks. One significant feature of SLF4J is its support for resource bundles, which facilitates internationalization (i18n) by enabling the localization of log messages.
To enable resource bundles in SLF4J, a properties file will be created to contain the localized messages. This file should follow a naming convention that corresponds to the locale it represents; for instance, message_en.properties for English. Subsequently, the SLF4J’s API will retrieve the localized messages from these resource bundles.
This post is a step-by-step guide to enabling resource bundle in Slf4j with Lombok.
The solution rides on the slf4j framework’s localization, which supports localization/internationalization.
https://www.slf4j.org/localization.html
First, define a custom logger that encapsulates the slf4jconfiguration to support the internationalization:
package io.app.common.logger;
import static java.util.Locale.UK;
import ch.qos.cal10n.MessageConveyor;
import org.slf4j.cal10n.LocLogger;
import org.slf4j.cal10n.LocLoggerFactory;
public class CustomLogger {
final static LocLoggerFactory locLoggerFactory =
new LocLoggerFactory(new MessageConveyor(UK));
public static LocLogger getLogger(Class<?> clazz) {
return locLoggerFactory.getLocLogger(clazz);
}
}For this post, the log message keys are kept under the enumResponseStatus. The logger will use the values to look up the corresponding message, defined in the section after.
package io.app.common;
import ch.qos.cal10n.BaseName;
import ch.qos.cal10n.Locale;
import ch.qos.cal10n.LocaleData;
@BaseName("log")
@LocaleData({@Locale("enGB")})
public enum ResponseStatus {
OK
}Define the src/main/resources/log_en_GB.properties to contain the messages that map to the ResponseStatus defined earlier:
OK=Task processed successfully [case={0}]