diff --git a/src/share/classes/java/util/logging/Logger.java b/src/share/classes/java/util/logging/Logger.java index e1f2bbaf5f82ef992504d70c892cda837bf85725..4e52c235c0cbc99a6acdad1e1d1f2a4d3b97ba4d 100644 --- a/src/share/classes/java/util/logging/Logger.java +++ b/src/share/classes/java/util/logging/Logger.java @@ -30,6 +30,7 @@ import java.util.*; 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 @@ import java.lang.ref.WeakReference; * for example a format string "{0} {1}" would format two parameters * as strings. *

+ * A set of methods alternatively take a "msgSupplier" instead of a "msg" + * argument. These methods take a {@link Supplier}{@code } 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: +

+
+   class DiagnosisMessages {
+     static String systemHealthStatus() {
+       // collect system health information
+       ...
+     }
+   }
+   ...
+   logger.log(Level.FINER, DiagnosisMessages.systemHealthStatus());
+ 
+ * 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. +
+
+   logger.log(Level.FINER, DiagnosisMessages::systemHealthStatus);
+ 
+ *

* 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 @@ -566,6 +594,27 @@ public class Logger { doLog(lr); } + /** + * Log a message, which is only to be constructed if the logging level + * is such that the message will actually be logged. + *

+ * 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. + *

+ * @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 msgSupplier) { + if (level.intValue() < levelValue || levelValue == offValue) { + return; + } + LogRecord lr = new LogRecord(level, msgSupplier.get()); + doLog(lr); + } + /** * Log a message, with one object parameter. *

@@ -615,7 +664,7 @@ public class Logger { * which is forwarded to all registered output handlers. *

* 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. *

@@ -632,6 +681,34 @@ public class Logger { doLog(lr); } + /** + * Log a lazily constructed message, with associated Throwable information. + *

+ * 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. + *

+ * 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. + *

+ * @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 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 //================================================================ @@ -659,6 +736,33 @@ public class Logger { doLog(lr); } + /** + * Log a lazily constructed message, specifying source class and method, + * with no arguments. + *

+ * 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. + *

+ * @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 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. @@ -721,7 +825,7 @@ public class Logger { * which is forwarded to all registered output handlers. *

* 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. *

@@ -732,7 +836,7 @@ public class Logger { * @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 @@ public class Logger { doLog(lr); } + /** + * Log a lazily constructed message, specifying source class and method, + * with associated Throwable information. + *

+ * 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. + *

+ * 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. + *

+ * @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 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 @@ public class Logger { * then the msg string is not localized. *

* 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. *

@@ -1014,7 +1152,7 @@ public class Logger { * LogRecord's message is set to "THROW". *

* 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. *

@@ -1149,6 +1287,130 @@ public class Logger { log(Level.FINEST, msg); } + //======================================================================= + // Start of simple convenience methods using level names as method names + // and use Supplier + //======================================================================= + + /** + * Log a SEVERE message, which is only to be constructed if the logging + * level is such that the message will actually be logged. + *

+ * 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. + *

+ * @param msgSupplier A function, which when called, produces the + * desired log message + * @since 1.8 + */ + public void severe(Supplier 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. + *

+ * 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. + *

+ * @param msgSupplier A function, which when called, produces the + * desired log message + * @since 1.8 + */ + public void warning(Supplier 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. + *

+ * 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. + *

+ * @param msgSupplier A function, which when called, produces the + * desired log message + * @since 1.8 + */ + public void info(Supplier 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. + *

+ * 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. + *

+ * @param msgSupplier A function, which when called, produces the + * desired log message + * @since 1.8 + */ + public void config(Supplier 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. + *

+ * 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. + *

+ * @param msgSupplier A function, which when called, produces the + * desired log message + * @since 1.8 + */ + public void fine(Supplier 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. + *

+ * 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. + *

+ * @param msgSupplier A function, which when called, produces the + * desired log message + * @since 1.8 + */ + public void finer(Supplier 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. + *

+ * 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. + *

+ * @param msgSupplier A function, which when called, produces the + * desired log message + * @since 1.8 + */ + public void finest(Supplier msgSupplier) { + log(Level.FINEST, msgSupplier); + } + //================================================================ // End of convenience methods //================================================================ diff --git a/test/java/util/logging/LoggerSupplierAPIsTest.java b/test/java/util/logging/LoggerSupplierAPIsTest.java new file mode 100644 index 0000000000000000000000000000000000000000..4333ba1801674bb604daba257c0bd8f004798d5e --- /dev/null +++ b/test/java/util/logging/LoggerSupplierAPIsTest.java @@ -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 { + 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 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 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); + } + } +}