foolhunger
foolhunger

Reputation: 345

java.util.logging.SimpileFormatter system property configuration

I'm learning Java logging recently, and in the javadoc, it says the SimpleFormatter can be configured using property "java.util.logging.SimpleFormatter.format".

In below code, I tried to "set the format" twice with System.setProperty(), but it seems won't work in the second attempt, the "formatterB" in below code will still use the format defined in "formatterA".

What's the reason for this, thanks.

public class Test {
    public static void main(String[] args) {
        try {
            Logger loggerA = Logger.getLogger("A");
            System.setProperty("java.util.logging.SimpleFormatter.format", "A: %1$tc %2$s%n%4$s: %5$s%6$s%n");  // first attempt
            Handler handlerA = new FileHandler("A.log", 0, 1, true);
            SimpleFormatter formatterA = new SimpleFormatter();
            handlerA.setFormatter(formatterA);
            loggerA.addHandler(handlerA);
            loggerA.info("Logger A info message");

            Logger loggerB = Logger.getLogger("B");
            System.setProperty("java.util.logging.SimpleFormatter.format", "B: %1$tc %2$s%n%4$s: %5$s%6$s%n");  // second attempt
            Handler handlerB = new FileHandler("B.log", 0, 1, true);
            SimpleFormatter formatterB = new SimpleFormatter();
            handlerB.setFormatter(formatterB);
            loggerB.addHandler(handlerB);
            loggerB.info("Logger B info message");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

Upvotes: 1

Views: 949

Answers (1)

jmehrens
jmehrens

Reputation: 11045

The SimpleFormatter stores the format in a static field that is stored once on class load. The format is used for all instances of the SimpleFormatter class.

You'll have to roll your own formatter class or classes to support multiple formats.

Upvotes: 2

Related Questions