Java logger - apostrophe issues with tokens
Asked Answered
W

2

5

I have some unexplained behavior with java.util.logging. Let's take a look at these two samples:

First:

boolean var = false;
log.log( Level.WARNING, "Cant {0}", new Object[] { var } );

output:

Cant false

Second:

boolean var = false;
log.log( Level.WARNING, "Can't {0}", new Object[] { var } );

output:

Can't {0}

Why does the inclusion of an apostrophe ( ' ) causes the logger not to expand the token?

Wiry answered 26/3, 2014 at 18:58 Comment(2)
Also, the first output seems like it should be Cant false.Parodist
@SotiriosDelimanolis log is a java.util.logging.Logger , you are right about the output, was posting in a hurry.Wiry
L
6

It appears that whatever logging mechanism you're using is using the MessageFormat class internally. If so, then you'll need to escape the apostrophe character, because it's a single-quote character. Single-quote characters are used to quote text that isn't meant to be interpreted.

MessageFormat javadocs:

Within a String, a pair of single quotes can be used to quote any arbitrary characters except single quotes. For example, pattern string "'{0}'" represents string "{0}", not a FormatElement. A single quote itself must be represented by doubled single quotes '' throughout a String.

(emphasis mine)

Try

log.log( Level.WARNING, "Can''t {0}", new Object[] { var } );

This code:

MessageFormat mf = new MessageFormat("Can''t {0}");
System.out.println(mf.format(new Object[] {false}));

yields this output:

Can't false
Lacework answered 26/3, 2014 at 19:5 Comment(1)
Yes, this is it! I thought it had something to do with escaping but tried \' instead of double single quotes.Wiry
N
1

{ and } are also potentially problems. This is why the NetBeans IDE hint to use message formats in log messages escapes these characters.

Besides

log.log(Level.WARNING, "Can''t {0}", new Object[] {var});

you can try simply and more readably

log.log(Level.WARNING, "Can’t {0}", new Object[] {var});

or just spell it out to begin with:

log.log(Level.WARNING, "Cannot {0}", new Object[] {var});
Numerate answered 25/10, 2017 at 15:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.