Friday, July 14, 2006

Internationalization of logging and error messages for the server side (cont'd)

I ended my previous blog with "Isn't there a better way"? Well... how would I like to use error messages in Java source code? I would simply want to write something like this:

String msg = msgcat.get("F1231: Could not open file {1} in directory {0}: {2}", dir, file, ex);
throw new IOException(msg, ex);
The advantages are clear:
  1. No switching to a different file to add the error message
  2. The error message is visible right there in the source code -- easy to review!
  3. It's easy to see that the arguments in {0}, {1} are correct   
But how are would we deal with the same error message (same error code) being used in multiple places in the source? Well... there's not a good anwer for that. Fortunately, error messages tend to be unique, i.e. rarely would the same error message be reused.

How is this source file internationalized? We need a tool! The tool will
  1. locate all error messages in the code base
  2. generate properties files for all desired languages if they don't exist     
  3. print out a list of all properties files that need to be localized
Here's what I would like to see as the output of the tool:
F1231 = Could not open file {1} in directory {0}: {2}
# F1231 = Could not open file {1} in directory {0}: {2}

so that a human translator can easily add the translations to the foreign properties files. As you can see, it includes the location (Java class) where the message was encountered.
# F1231 = Could not open file {1} in directory {0}: {2}
F1231 = Bestand {1} in lijst {0} kon niet geopend worden: {2}
Ofcourse the tool would have a way of handling if you would change the error message in the source code. The translated properties file would look like this:
# F1231 = File {1} in directory {0} could not be opened: {2}
# F1231 = Could not open file {1} in directory {0}: {2}
F1231 = Bestand {1} in lijst {0} kon niet geopend worden: {2}
Any ideas on how to build this tool?


Tim Foster said...

Sounds like you want the Netbeans i18n module, or at least should start with that, and build on it if you need to. The Open Language Tools project has much of the smarts for dealing with message files, checking for pre-translated messages, etc. but Netbeans itself already has all the Java source code parsing stuff taken care of - best not reinvent the wheel...

Tim Foster said...

Oops, forgot to add a link to the Open Language Tools project - here you go :