• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

java.util.logging: MessageFormat-style parameters or String.format()/printf style

 
Faraz Syed
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am wondering if there are any performance or efficiency reasons to use MessageFormat-style parameters to log messages e.g.:



as opposed to using String.format() to format a log message containing printf-style specifiers:



In all the documentation/tutorials I've found for the java.util.logging facility, I haven't come across much info on using the MessageFormat-style approach for passing parameters to log messages.

I'd like to know what are the best practices for parameterized logging when using the java.util.logging for Logging.

Thanks.
 
Jacob Anawalt
Ranch Hand
Posts: 64
Linux Netbeans IDE Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Within the context of logging performance and efficiency, an advantage of the MessageFormat example over the String.format is that if logger.isLoggable(Level.FINER) is false, the MessageFormat example may do less work. It will create a new Object array with the values of transactionId and will call getName like the String.format example, but it may skip the string formatting.

MessageFormat may be a little heavier than String.format so your performance may be better if you used String.format, StringBuilder or String concatenation (+) in a loggable test if you're not logging FINER all the time. Especially if you have no localization needs in logging. Eg:



The SLF4J library encourages the parameterized logging and has a built-in formatter that is lighter than MessageFormat. They address performance for the not-logging case in their FAQ entry titled "What is the fastest way of (not) logging?". There are some long drawn-out discussions in the Hadoop project about testing if a logging level is enabled or not, like HADOOP-6884, that shed some more insights on this subject.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic