How to format a log message

I would like to format my log message before printing it on the Logger.fine console

eg. How to format "{0} has {1} apples with it," so the inputs are John and 10

I would prefer the logging framework that provides this solution, and I do not want to format these messages separately. The specific JDK6 logging classes do not seem to have this level of granularity.

+4
source share
3 answers

Use MessageFormat :

String s = MessageFormat.format("{0} has {1} apples with him", "John", 10); 

or String.format :

 String s = String.format("%1$s has %2$d apples with him", "John", 10); 
+12
source

Even with the simple JDK protocol, you can use Formatter to handle formatting of log messages with parameters.

For a (simplified) example:

 public class MyFormatter extends Formatter { /** * @see java.util.logging.Formatter#format(java.util.logging.LogRecord) */ @Override public String format(final LogRecord record) { return MessageFormat.format(record.getMessage(), record.getParameters()); } } 

Then, to use it, you can configure the logging.properties file with:

 java.util.logging.ConsoleHandler.formatter = com.example.MyFormatter 
+4
source

Just use String.format :

 String.format ("%s has %s apples with him", "John", "10"); 
+1
source

All Articles