Winter
Winter

Reputation: 1490

java.util.logging message template question

NetBeans recommended that I change the way that logging statements that have string concatenation are written, stating Convert string concatenation to a message template so that a statement such as:

log.severe("Completed at:  " + new Date());

got changed to

log.log(Level.SEVERE, "Completed at:  {0}", new Date());

The problem is that now the Date doesn't get printed. Instead, the string "{0}" literatlly gets printed instead. Is there something else I was suppose to do?

Upvotes: 5

Views: 5234

Answers (2)

Maine
Maine

Reputation: 1878

Assuming that the code snippet you posted is not the original code that was causing problems... Having a single apostrophe in your message will cause the type of a problem you described. java.util.logging.Logger.log passes the message to java.text.MessageFormat which requires you to escape apostrophes.

For example:

log.log( Level.FINE, "Can't handle {0}.", id );
log.log( Level.FINE, "Can''t handle {0}.", id );

Logs:

Cant handle {0}.
Can't handle ID0001.

Upvotes: 4

jdmichal
jdmichal

Reputation: 11152

I know that PrintStream has a format method that works that way, though Java uses the C-like % prefix instead of the C#-like {} wrapper. But Logger has no such method. You are instead invoking an override of log which in my experience only logs the string exactly as given, and does nothing with the Object parameter.

Upvotes: 0

Related Questions