Localize log messages

You can assign a ResourceBundle with a logger. If you don’t, it will inherit the ResourceBundle from its parent. The following example localizes a message based on the current locale. Comment out the first line and it will use the default locale (eg. en_US) and hence our ListResourceBundle MyLogResources.

Notice that you can set MessageFormat parameters ({0}, {1}, …) by using another form of the log method.

Main.java:

import java.util.logging.*;
import java.util.*;
import java.io.*;
 
public class Main
{
   public static void main(String argv[]) {
      Locale.setDefault(new Locale("fr", "", ""));
      Logger logger = Logger.getLogger("main", "MyLogResources");
      logger.setUseParentHandlers(false);
      logger.setLevel(Level.ALL);
 
      ConsoleHandler consoleHandler = new ConsoleHandler();
      consoleHandler.setLevel(Level.ALL);
      logger.addHandler(consoleHandler);
 
      logger.severe("SEVERE_ERROR");
      logger.log(Level.WARNING, "FILE_NOT_FOUND", new Object[] { "autoexec.bat" });
      logger.info("OTHER_INFO");
   }
}

MyLogResources.java:

import java.util.*;
 
public class MyLogResources extends ListResourceBundle {
   public Object[][] getContents() {
      return contents;
   }
 
   static final Object[][] contents = {
      {"SEVERE_ERROR",   "A severe error occurred"},
      {"FILE_NOT_FOUND", "File {0} was not found"}
   };
}

MyLogResources_fr.java:

import java.util.*;
 
public class MyLogResources_fr extends ListResourceBundle {
   public Object[][] getContents() {
      return contents;
   }
 
   static final Object[][] contents = {
      {"SEVERE_ERROR",   "Il y avait un erreur tres grave"},
      {"FILE_NOT_FOUND", "Le fichier {0} n'est pas la"}
   };
}

Running java Main outputs:

21 janv. 2002 00:02:21 Main main
GRAVE: Il y avait un erreur tres grave
21 janv. 2002 00:02:21 Main main
ATTENTION: Le fichier autoexec.bat nest pas la
21 janv. 2002 00:02:21 Main main
INFO: OTHER_INFO