Search code examples
javanewlinemessageformat

Does Java MessageFormat have a platform lineseparator like String.format does?


This is a long shot, but I'm hoping to replace the newline literals in MessageFormat code like

LOG.log(INFO, "message={0}\nAnd extra blank line\n", new String[]{message});

with a platform-independent pattern. The String.format() pattern %n does not work for Logger or MessageFormat. I'd like to avoid passing System.lineseperator as an argument like this:

LOG.log(INFO, "message={0}{1}And a blank line{1}",new String[]{message, System.lineSeparator()});

I don't see any mention of newline or lineseparator in the docs for MessageFormat, but perhaps it is mentioned somewhere else. https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/MessageFormat.html


Solution

  • Does Java MessageFormat have a platform lineseparator like String.format does?

    According to my reading of the code, the answer is No.

    And there aren't any extant RFEs or Bug reports about this that I can see in the Java or OpenJDK Bug trackers1.

    However, as Joop notes, since you are actually asking this in the context of logging, there are a few other ways to solve this (though not all will be practical):

    • Ignore the problem. These messages are going into log files. Maybe it doesn't really matter that the line separators in messages in the log files don't always match the platform.
    • Create a custom subclass of MessageFormat that recognizes a syntax that means "platform specific line separator".
    • Handle the line separators by translating them in a custom log message appender or formatter; e.g.
      • Translate all line separators of the "wrong kind".
      • Recognize and translate a magic character sequence ...
    • Change to a different logging framework that uses java.util.Formatter for message construction. AFAIK, most modern frameworks do.
    • Submit an RFE.

    1 - You could read that as "evidence" of how little use there is of MessageFormat in real world / modern applications, or how few people use it in contexts where line separators matter.


    @Bohemian commented:

    Why do you want to avoid "passing System.lineseparator as an argument"?

    I would have thought that was self-evident. It is clunky.