8005632: Extend java.util.Logger to use Supplier<String> for messages
authormduigou
Fri, 25 Jan 2013 16:13:32 -0800
changeset 15310 77bdd8c8467e
parent 15309 b585dca79d0b
child 15311 be0ff4a719bf
8005632: Extend java.util.Logger to use Supplier<String> for messages Reviewed-by: briangoetz, mduigou Contributed-by: henry.jen@oracle.com
jdk/src/share/classes/java/util/logging/Logger.java
jdk/test/java/util/logging/LoggerSupplierAPIsTest.java
--- a/jdk/src/share/classes/java/util/logging/Logger.java	Fri Jan 25 11:52:10 2013 -0800
+++ b/jdk/src/share/classes/java/util/logging/Logger.java	Fri Jan 25 16:13:32 2013 -0800
@@ -30,6 +30,7 @@
 import java.util.concurrent.CopyOnWriteArrayList;
 import java.security.*;
 import java.lang.ref.WeakReference;
+import java.util.function.Supplier;
 
 /**
  * A Logger object is used to log messages for a specific
@@ -96,6 +97,33 @@
  * for example a format string "{0} {1}" would format two parameters
  * as strings.
  * <p>
+ * A set of methods alternatively take a "msgSupplier" instead of a "msg"
+ * argument.  These methods take a {@link Supplier}{@code <String>} function
+ * which is invoked to construct the desired log message only when the message
+ * actually is to be logged based on the effective log level thus eliminating
+ * unnecessary message construction. For example, if the developer wants to
+ * log system health status for diagnosis, with the String-accepting version,
+ * the code would look like:
+ <code><pre>
+
+   class DiagnosisMessages {
+     static String systemHealthStatus() {
+       // collect system health information
+       ...
+     }
+   }
+   ...
+   logger.log(Level.FINER, DiagnosisMessages.systemHealthStatus());
+ </pre></code>
+ * With the above code, the health status is collected unnecessarily even when
+ * the log level FINER is disabled. With the Supplier-accepting version as
+ * below, the status will only be collected when the log level FINER is
+ * enabled.
+ <code><pre>
+
+   logger.log(Level.FINER, DiagnosisMessages::systemHealthStatus);
+ </pre></code>
+ * <p>
  * When mapping ResourceBundle names to ResourceBundles, the Logger
  * will first try to use the Thread's ContextClassLoader.  If that
  * is null it will try the SystemClassLoader instead.  As a temporary
@@ -567,6 +595,27 @@
     }
 
     /**
+     * Log a message, which is only to be constructed if the logging level
+     * is such that the message will actually be logged.
+     * <p>
+     * If the logger is currently enabled for the given message
+     * level then the message is constructed by invoking the provided
+     * supplier function and forwarded to all the registered output
+     * Handler objects.
+     * <p>
+     * @param   level   One of the message level identifiers, e.g., SEVERE
+     * @param   msgSupplier   A function, which when called, produces the
+     *                        desired log message
+     */
+    public void log(Level level, Supplier<String> msgSupplier) {
+        if (level.intValue() < levelValue || levelValue == offValue) {
+            return;
+        }
+        LogRecord lr = new LogRecord(level, msgSupplier.get());
+        doLog(lr);
+    }
+
+    /**
      * Log a message, with one object parameter.
      * <p>
      * If the logger is currently enabled for the given message
@@ -615,7 +664,7 @@
      * which is forwarded to all registered output handlers.
      * <p>
      * Note that the thrown argument is stored in the LogRecord thrown
-     * property, rather than the LogRecord parameters property.  Thus is it
+     * property, rather than the LogRecord parameters property.  Thus it is
      * processed specially by output Formatters and is not treated
      * as a formatting parameter to the LogRecord message property.
      * <p>
@@ -632,6 +681,34 @@
         doLog(lr);
     }
 
+    /**
+     * Log a lazily constructed message, with associated Throwable information.
+     * <p>
+     * If the logger is currently enabled for the given message level then the
+     * message is constructed by invoking the provided supplier function. The
+     * message and the given {@link Throwable} are then stored in a {@link
+     * LogRecord} which is forwarded to all registered output handlers.
+     * <p>
+     * Note that the thrown argument is stored in the LogRecord thrown
+     * property, rather than the LogRecord parameters property.  Thus it is
+     * processed specially by output Formatters and is not treated
+     * as a formatting parameter to the LogRecord message property.
+     * <p>
+     * @param   level   One of the message level identifiers, e.g., SEVERE
+     * @param   thrown  Throwable associated with log message.
+     * @param   msgSupplier   A function, which when called, produces the
+     *                        desired log message
+     * @since   1.8
+     */
+    public void log(Level level, Throwable thrown, Supplier<String> msgSupplier) {
+        if (level.intValue() < levelValue || levelValue == offValue) {
+            return;
+        }
+        LogRecord lr = new LogRecord(level, msgSupplier.get());
+        lr.setThrown(thrown);
+        doLog(lr);
+    }
+
     //================================================================
     // Start of convenience methods WITH className and methodName
     //================================================================
@@ -660,6 +737,33 @@
     }
 
     /**
+     * Log a lazily constructed message, specifying source class and method,
+     * with no arguments.
+     * <p>
+     * If the logger is currently enabled for the given message
+     * level then the message is constructed by invoking the provided
+     * supplier function and forwarded to all the registered output
+     * Handler objects.
+     * <p>
+     * @param   level   One of the message level identifiers, e.g., SEVERE
+     * @param   sourceClass    name of class that issued the logging request
+     * @param   sourceMethod   name of method that issued the logging request
+     * @param   msgSupplier   A function, which when called, produces the
+     *                        desired log message
+     * @since   1.8
+     */
+    public void logp(Level level, String sourceClass, String sourceMethod,
+                     Supplier<String> msgSupplier) {
+        if (level.intValue() < levelValue || levelValue == offValue) {
+            return;
+        }
+        LogRecord lr = new LogRecord(level, msgSupplier.get());
+        lr.setSourceClassName(sourceClass);
+        lr.setSourceMethodName(sourceMethod);
+        doLog(lr);
+    }
+
+    /**
      * Log a message, specifying source class and method,
      * with a single object parameter to the log message.
      * <p>
@@ -721,7 +825,7 @@
      * which is forwarded to all registered output handlers.
      * <p>
      * Note that the thrown argument is stored in the LogRecord thrown
-     * property, rather than the LogRecord parameters property.  Thus is it
+     * property, rather than the LogRecord parameters property.  Thus it is
      * processed specially by output Formatters and is not treated
      * as a formatting parameter to the LogRecord message property.
      * <p>
@@ -732,7 +836,7 @@
      * @param   thrown  Throwable associated with log message.
      */
     public void logp(Level level, String sourceClass, String sourceMethod,
-                                                        String msg, Throwable thrown) {
+                     String msg, Throwable thrown) {
         if (level.intValue() < levelValue || levelValue == offValue) {
             return;
         }
@@ -743,6 +847,40 @@
         doLog(lr);
     }
 
+    /**
+     * Log a lazily constructed message, specifying source class and method,
+     * with associated Throwable information.
+     * <p>
+     * If the logger is currently enabled for the given message level then the
+     * message is constructed by invoking the provided supplier function. The
+     * message and the given {@link Throwable} are then stored in a {@link
+     * LogRecord} which is forwarded to all registered output handlers.
+     * <p>
+     * Note that the thrown argument is stored in the LogRecord thrown
+     * property, rather than the LogRecord parameters property.  Thus it is
+     * processed specially by output Formatters and is not treated
+     * as a formatting parameter to the LogRecord message property.
+     * <p>
+     * @param   level   One of the message level identifiers, e.g., SEVERE
+     * @param   sourceClass    name of class that issued the logging request
+     * @param   sourceMethod   name of method that issued the logging request
+     * @param   thrown  Throwable associated with log message.
+     * @param   msgSupplier   A function, which when called, produces the
+     *                        desired log message
+     * @since   1.8
+     */
+    public void logp(Level level, String sourceClass, String sourceMethod,
+                     Throwable thrown, Supplier<String> msgSupplier) {
+        if (level.intValue() < levelValue || levelValue == offValue) {
+            return;
+        }
+        LogRecord lr = new LogRecord(level, msgSupplier.get());
+        lr.setSourceClassName(sourceClass);
+        lr.setSourceMethodName(sourceMethod);
+        lr.setThrown(thrown);
+        doLog(lr);
+    }
+
 
     //=========================================================================
     // Start of convenience methods WITH className, methodName and bundle name.
@@ -869,7 +1007,7 @@
      * then the msg string is not localized.
      * <p>
      * Note that the thrown argument is stored in the LogRecord thrown
-     * property, rather than the LogRecord parameters property.  Thus is it
+     * property, rather than the LogRecord parameters property.  Thus it is
      * processed specially by output Formatters and is not treated
      * as a formatting parameter to the LogRecord message property.
      * <p>
@@ -1014,7 +1152,7 @@
      * LogRecord's message is set to "THROW".
      * <p>
      * Note that the thrown argument is stored in the LogRecord thrown
-     * property, rather than the LogRecord parameters property.  Thus is it
+     * property, rather than the LogRecord parameters property.  Thus it is
      * processed specially by output Formatters and is not treated
      * as a formatting parameter to the LogRecord message property.
      * <p>
@@ -1149,6 +1287,130 @@
         log(Level.FINEST, msg);
     }
 
+    //=======================================================================
+    // Start of simple convenience methods using level names as method names
+    // and use Supplier<String>
+    //=======================================================================
+
+    /**
+     * Log a SEVERE message, which is only to be constructed if the logging
+     * level is such that the message will actually be logged.
+     * <p>
+     * If the logger is currently enabled for the SEVERE message
+     * level then the message is constructed by invoking the provided
+     * supplier function and forwarded to all the registered output
+     * Handler objects.
+     * <p>
+     * @param   msgSupplier   A function, which when called, produces the
+     *                        desired log message
+     * @since   1.8
+     */
+    public void severe(Supplier<String> msgSupplier) {
+        log(Level.SEVERE, msgSupplier);
+    }
+
+    /**
+     * Log a WARNING message, which is only to be constructed if the logging
+     * level is such that the message will actually be logged.
+     * <p>
+     * If the logger is currently enabled for the WARNING message
+     * level then the message is constructed by invoking the provided
+     * supplier function and forwarded to all the registered output
+     * Handler objects.
+     * <p>
+     * @param   msgSupplier   A function, which when called, produces the
+     *                        desired log message
+     * @since   1.8
+     */
+    public void warning(Supplier<String> msgSupplier) {
+        log(Level.WARNING, msgSupplier);
+    }
+
+    /**
+     * Log a INFO message, which is only to be constructed if the logging
+     * level is such that the message will actually be logged.
+     * <p>
+     * If the logger is currently enabled for the INFO message
+     * level then the message is constructed by invoking the provided
+     * supplier function and forwarded to all the registered output
+     * Handler objects.
+     * <p>
+     * @param   msgSupplier   A function, which when called, produces the
+     *                        desired log message
+     * @since   1.8
+     */
+    public void info(Supplier<String> msgSupplier) {
+        log(Level.INFO, msgSupplier);
+    }
+
+    /**
+     * Log a CONFIG message, which is only to be constructed if the logging
+     * level is such that the message will actually be logged.
+     * <p>
+     * If the logger is currently enabled for the CONFIG message
+     * level then the message is constructed by invoking the provided
+     * supplier function and forwarded to all the registered output
+     * Handler objects.
+     * <p>
+     * @param   msgSupplier   A function, which when called, produces the
+     *                        desired log message
+     * @since   1.8
+     */
+    public void config(Supplier<String> msgSupplier) {
+        log(Level.CONFIG, msgSupplier);
+    }
+
+    /**
+     * Log a FINE message, which is only to be constructed if the logging
+     * level is such that the message will actually be logged.
+     * <p>
+     * If the logger is currently enabled for the FINE message
+     * level then the message is constructed by invoking the provided
+     * supplier function and forwarded to all the registered output
+     * Handler objects.
+     * <p>
+     * @param   msgSupplier   A function, which when called, produces the
+     *                        desired log message
+     * @since   1.8
+     */
+    public void fine(Supplier<String> msgSupplier) {
+        log(Level.FINE, msgSupplier);
+    }
+
+    /**
+     * Log a FINER message, which is only to be constructed if the logging
+     * level is such that the message will actually be logged.
+     * <p>
+     * If the logger is currently enabled for the FINER message
+     * level then the message is constructed by invoking the provided
+     * supplier function and forwarded to all the registered output
+     * Handler objects.
+     * <p>
+     * @param   msgSupplier   A function, which when called, produces the
+     *                        desired log message
+     * @since   1.8
+     */
+    public void finer(Supplier<String> msgSupplier) {
+        log(Level.FINER, msgSupplier);
+    }
+
+    /**
+     * Log a FINEST message, which is only to be constructed if the logging
+     * level is such that the message will actually be logged.
+     * <p>
+     * If the logger is currently enabled for the FINEST message
+     * level then the message is constructed by invoking the provided
+     * supplier function and forwarded to all the registered output
+     * Handler objects.
+     * <p>
+     * @param   msgSupplier   A function, which when called, produces the
+     *                        desired log message
+     * @since   1.8
+     */
+    public void finest(Supplier<String> msgSupplier) {
+        log(Level.FINEST, msgSupplier);
+    }
+
     //================================================================
     // End of convenience methods
     //================================================================
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/util/logging/LoggerSupplierAPIsTest.java	Fri Jan 25 16:13:32 2013 -0800
@@ -0,0 +1,264 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8005263
+ * @run testng LoggerSupplierAPIsTest
+ */
+
+import java.util.logging.Logger;
+import java.util.logging.Level;
+import java.util.logging.Handler;
+import java.util.logging.LogRecord;
+import java.util.function.Supplier;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Collections;
+
+import org.testng.annotations.Test;
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertTrue;
+
+@Test(groups="unit")
+public class LoggerSupplierAPIsTest {
+    static class CountingSupplier implements Supplier<String> {
+        AtomicInteger sno = new AtomicInteger();
+
+        @Override
+        public String get() {
+            return "Log message " + sno.getAndIncrement();
+        }
+
+        public int getCount() { return sno.get(); }
+        public void reset() { sno.set(0); }
+    }
+
+    static class CountingHandler extends Handler {
+        AtomicInteger count = new AtomicInteger();
+        ArrayList<LogRecord> ar = new ArrayList<>();
+
+        @Override
+        public void close() { reset(); }
+
+        @Override
+        public void flush() { reset(); }
+
+        @Override
+        public void publish(LogRecord lr) {
+            // Can do some more assertion here?
+            // System.out.println(lr.getMessage());
+            count.incrementAndGet();
+        }
+
+        public int getCount() {
+            return count.get();
+        }
+
+        public List<LogRecord> getLogs() {
+            return Collections.unmodifiableList(ar);
+        }
+
+        public void reset() {
+            count.set(0);
+            ar.clear();
+        }
+    }
+
+    static class HelperEx extends Exception {
+        final Level level;
+        HelperEx(Level l) { level = l; }
+        Level getLevel() { return level; }
+    }
+
+    static class SystemInfo {
+        public static String Java() {
+            return "Java: " + System.getProperty("java.version") +
+                   " installed at " + System.getProperty("java.home");
+        }
+
+        public static String OS() {
+            return "OS: " + System.getProperty("os.name") +
+                   " " + System.getProperty("os.version") +
+                   " " + System.getProperty("os.arch");
+        }
+    }
+
+    static final CountingSupplier supplier = new CountingSupplier();
+    static final CountingHandler handler = new CountingHandler();
+    static final Logger logger;
+    static final Level[] levels = { Level.ALL, Level.OFF, Level.SEVERE,
+                                    Level.WARNING, Level.INFO, Level.CONFIG,
+                                    Level.FINE, Level.FINER, Level.FINEST };
+    static final int[] invokes = { 7, 0, 1, 2, 3, 4, 5, 6, 7 };
+    static final int[] log_count = { 10, 0, 1, 2, 3, 4, 6, 8, 10 };
+
+    static {
+        logger = Logger.getLogger("LoggerSupplierApisTest");
+        logger.setUseParentHandlers(false);
+        logger.addHandler(handler);
+    }
+
+    public void setup() {
+        supplier.reset();
+        handler.reset();
+    }
+
+    private void testLog() {
+        logger.log(Level.SEVERE, supplier);
+        logger.log(Level.WARNING, supplier);
+        logger.log(Level.INFO, supplier);
+        logger.log(Level.CONFIG, supplier);
+        logger.log(Level.FINE, supplier);
+        logger.log(Level.FINER, supplier);
+        logger.log(Level.FINEST, supplier);
+        // Lambda expression
+        logger.log(Level.FINE, () ->
+            "Timestamp: " + System.currentTimeMillis() +
+            ", user home directory:  " + System.getProperty("user.home"));
+        // Method reference
+        logger.log(Level.FINER, SystemInfo::Java);
+        logger.log(Level.FINEST, SystemInfo::OS);
+    }
+
+    private void testLogThrown() {
+        logger.log(Level.SEVERE, new HelperEx(Level.SEVERE), supplier);
+        logger.log(Level.WARNING, new HelperEx(Level.WARNING), supplier);
+        logger.log(Level.INFO, new HelperEx(Level.INFO), supplier);
+        logger.log(Level.CONFIG, new HelperEx(Level.CONFIG), supplier);
+        logger.log(Level.FINE, new HelperEx(Level.FINE), supplier);
+        logger.log(Level.FINER, new HelperEx(Level.FINER), supplier);
+        logger.log(Level.FINEST, new HelperEx(Level.FINEST), supplier);
+        // Lambda expression
+        logger.log(Level.FINE, new HelperEx(Level.FINE), () ->
+            "Timestamp: " + System.currentTimeMillis() +
+            ", user home directory:  " + System.getProperty("user.home"));
+        // Method reference
+        logger.log(Level.FINER, new HelperEx(Level.FINER), SystemInfo::Java);
+        logger.log(Level.FINEST, new HelperEx(Level.FINEST), SystemInfo::OS);
+    }
+
+    private void testLogp() {
+        final String cls = getClass().getName();
+        final String mtd = "testLogp";
+
+        logger.logp(Level.SEVERE, cls, mtd, supplier);
+        logger.logp(Level.WARNING, cls, mtd, supplier);
+        logger.logp(Level.INFO, cls, mtd, supplier);
+        logger.logp(Level.CONFIG, cls, mtd, supplier);
+        logger.logp(Level.FINE, cls, mtd, supplier);
+        logger.logp(Level.FINER, cls, mtd, supplier);
+        logger.logp(Level.FINEST, cls, mtd, supplier);
+        // Lambda expression
+        logger.logp(Level.FINE, cls, mtd, () ->
+            "Timestamp: " + System.currentTimeMillis() +
+            ", user home directory:  " + System.getProperty("user.home"));
+        // Method reference
+        logger.logp(Level.FINER, cls, mtd, SystemInfo::Java);
+        logger.logp(Level.FINEST, cls, mtd, SystemInfo::OS);
+    }
+
+    private void testLogpThrown() {
+        final String cls = getClass().getName();
+        final String mtd = "testLogpThrown";
+
+        logger.logp(Level.SEVERE, cls, mtd, new HelperEx(Level.SEVERE), supplier);
+        logger.logp(Level.WARNING, cls, mtd, new HelperEx(Level.WARNING), supplier);
+        logger.logp(Level.INFO, cls, mtd, new HelperEx(Level.INFO), supplier);
+        logger.logp(Level.CONFIG, cls, mtd, new HelperEx(Level.CONFIG), supplier);
+        logger.logp(Level.FINE, cls, mtd, new HelperEx(Level.FINE), supplier);
+        logger.logp(Level.FINER, cls, mtd, new HelperEx(Level.FINER), supplier);
+        logger.logp(Level.FINEST, cls, mtd, new HelperEx(Level.FINEST), supplier);
+        // Lambda expression
+        logger.logp(Level.FINE, cls, mtd, new HelperEx(Level.FINE), () ->
+            "Timestamp: " + System.currentTimeMillis() +
+            ", user home directory:  " + System.getProperty("user.home"));
+        // Method reference
+        logger.logp(Level.FINER, cls, mtd, new HelperEx(Level.FINER), SystemInfo::Java);
+        logger.logp(Level.FINEST, cls, mtd, new HelperEx(Level.FINEST), SystemInfo::OS);
+    }
+
+    private void testLevelConvenientMethods() {
+        logger.severe(supplier);
+        logger.warning(supplier);
+        logger.info(supplier);
+        logger.config(supplier);
+        logger.fine(supplier);
+        logger.finer(supplier);
+        logger.finest(supplier);
+        // Lambda expression
+        logger.fine(() ->
+            "Timestamp: " + System.currentTimeMillis() +
+            ", user home directory:  " + System.getProperty("user.home"));
+        // Method reference
+        logger.finer(SystemInfo::Java);
+        logger.finest(SystemInfo::OS);
+    }
+
+    private void validate(int index, boolean thrown, String methodName) {
+        assertEquals(supplier.getCount(), invokes[index]);
+        assertEquals(handler.getCount(), log_count[index]);
+        // Verify associated Throwable is right
+        if (thrown) {
+            for (LogRecord r: handler.getLogs()) {
+                assertTrue(r.getThrown() instanceof HelperEx, "Validate Thrown");
+                HelperEx e = (HelperEx) r.getThrown();
+                assertEquals(r.getLevel(), e.getLevel(), "Validate Thrown Log Level");
+            }
+        }
+
+        if (methodName != null) {
+            for (LogRecord r: handler.getLogs()) {
+                assertEquals(r.getSourceClassName(), getClass().getName());
+                assertEquals(r.getSourceMethodName(), methodName);
+            }
+        }
+    }
+
+    public void verifyLogLevel() {
+        for (int i = 0; i < levels.length; i++) {
+            logger.setLevel(levels[i]);
+
+            setup();
+            testLog();
+            validate(i, false, null);
+
+            setup();
+            testLogThrown();
+            validate(i, true, null);
+
+            setup();
+            testLogp();
+            validate(i, false, "testLogp");
+
+            setup();
+            testLogpThrown();
+            validate(i, true, "testLogpThrown");
+
+            setup();
+            testLevelConvenientMethods();
+            validate(i, false, null);
+        }
+    }
+}