src/java.logging/share/classes/java/util/logging/LogManager.java

Print this page


   1 /*
   2  * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 
  27 package java.util.logging;
  28 
  29 import java.io.*;
  30 import java.util.*;
  31 import java.security.*;
  32 import java.lang.ref.ReferenceQueue;
  33 import java.lang.ref.WeakReference;

  34 import sun.misc.JavaAWTAccess;
  35 import sun.misc.SharedSecrets;
  36 
  37 /**
  38  * There is a single global LogManager object that is used to
  39  * maintain a set of shared state about Loggers and log services.
  40  * <p>
  41  * This LogManager object:
  42  * <ul>
  43  * <li> Manages a hierarchical namespace of Logger objects.  All
  44  *      named Loggers are stored in this namespace.
  45  * <li> Manages a set of logging control properties.  These are
  46  *      simple key-value pairs that can be used by Handlers and
  47  *      other logging objects to configure themselves.
  48  * </ul>
  49  * <p>
  50  * The global LogManager object can be retrieved using LogManager.getLogManager().
  51  * The LogManager object is created during class initialization and
  52  * cannot subsequently be changed.
  53  * <p>


 152     private volatile Properties props = new Properties();
 153     private final static Level defaultLevel = Level.INFO;
 154 
 155     // LoggerContext for system loggers and user loggers
 156     private final LoggerContext systemContext = new SystemLoggerContext();
 157     private final LoggerContext userContext = new LoggerContext();
 158     // non final field - make it volatile to make sure that other threads
 159     // will see the new value once ensureLogManagerInitialized() has finished
 160     // executing.
 161     private volatile Logger rootLogger;
 162     // Have we done the primordial reading of the configuration file?
 163     // (Must be done after a suitable amount of java.lang.System
 164     // initialization has been done)
 165     private volatile boolean readPrimordialConfiguration;
 166     // Have we initialized global (root) handlers yet?
 167     // This gets set to false in readConfiguration
 168     private boolean initializedGlobalHandlers = true;
 169     // True if JVM death is imminent and the exit hook has been called.
 170     private boolean deathImminent;
 171 



 172     static {
 173         manager = AccessController.doPrivileged(new PrivilegedAction<LogManager>() {
 174             @Override
 175             public LogManager run() {
 176                 LogManager mgr = null;
 177                 String cname = null;
 178                 try {
 179                     cname = System.getProperty("java.util.logging.manager");
 180                     if (cname != null) {
 181                         try {
 182                             Class<?> clz = ClassLoader.getSystemClassLoader()
 183                                     .loadClass(cname);
 184                             mgr = (LogManager) clz.newInstance();
 185                         } catch (ClassNotFoundException ex) {
 186                             Class<?> clz = Thread.currentThread()
 187                                     .getContextClassLoader().loadClass(cname);
 188                             mgr = (LogManager) clz.newInstance();
 189                         }
 190                     }
 191                 } catch (Exception ex) {


1151      * return value from {@code LogManager.getLogger()} for null to properly
1152      * handle the case where the Logger has been garbage collected in the
1153      * time since its name was returned by this method.
1154      *
1155      * @return  enumeration of logger name strings
1156      */
1157     public Enumeration<String> getLoggerNames() {
1158         return getUserContext().getLoggerNames();
1159     }
1160 
1161     /**
1162      * Reinitialize the logging properties and reread the logging configuration.
1163      * <p>
1164      * The same rules are used for locating the configuration properties
1165      * as are used at startup.  So normally the logging properties will
1166      * be re-read from the same file that was used at startup.
1167      * <P>
1168      * Any log level definitions in the new configuration file will be
1169      * applied using Logger.setLevel(), if the target Logger exists.
1170      * <p>
1171      * A PropertyChangeEvent will be fired after the properties are read.

1172      *
1173      * @exception  SecurityException  if a security manager exists and if
1174      *             the caller does not have LoggingPermission("control").
1175      * @exception  IOException if there are IO problems reading the configuration.
1176      */
1177     public void readConfiguration() throws IOException, SecurityException {
1178         checkPermission();
1179 
1180         // if a configuration class is specified, load it and use it.
1181         String cname = System.getProperty("java.util.logging.config.class");
1182         if (cname != null) {
1183             try {
1184                 // Instantiate the named class.  It is its constructor's
1185                 // responsibility to initialize the logging configuration, by
1186                 // calling readConfiguration(InputStream) with a suitable stream.
1187                 try {
1188                     Class<?> clz = ClassLoader.getSystemClassLoader().loadClass(cname);
1189                     clz.newInstance();
1190                     return;
1191                 } catch (ClassNotFoundException ex) {


1285                 }
1286                 if (hands.charAt(end) == ',') {
1287                     break;
1288                 }
1289                 end++;
1290             }
1291             String word = hands.substring(ix, end);
1292             ix = end+1;
1293             word = word.trim();
1294             if (word.length() == 0) {
1295                 continue;
1296             }
1297             result.add(word);
1298         }
1299         return result.toArray(new String[result.size()]);
1300     }
1301 
1302     /**
1303      * Reinitialize the logging properties and reread the logging configuration
1304      * from the given stream, which should be in java.util.Properties format.
1305      * A PropertyChangeEvent will be fired after the properties are read.

1306      * <p>
1307      * Any log level definitions in the new configuration file will be
1308      * applied using Logger.setLevel(), if the target Logger exists.
1309      *
1310      * @param ins       stream to read properties from
1311      * @exception  SecurityException  if a security manager exists and if
1312      *             the caller does not have LoggingPermission("control").
1313      * @exception  IOException if there are problems reading from the stream.
1314      */
1315     public void readConfiguration(InputStream ins) throws IOException, SecurityException {
1316         checkPermission();
1317         reset();
1318 
1319         // Load the properties
1320         props.load(ins);
1321         // Instantiate new configuration objects.
1322         String names[] = parseClassNames("config");
1323 
1324         for (String word : names) {
1325             try {
1326                 Class<?> clz = ClassLoader.getSystemClassLoader().loadClass(word);
1327                 clz.newInstance();
1328             } catch (Exception ex) {
1329                 System.err.println("Can't load config class \"" + word + "\"");
1330                 System.err.println("" + ex);
1331                 // ex.printStackTrace();
1332             }
1333         }
1334 
1335         // Set levels on any pre-existing loggers, based on the new properties.
1336         setLevelsOnExistingLoggers();
1337 


1338         // Note that we need to reinitialize global handles when
1339         // they are first referenced.
1340         synchronized (this) {
1341             initializedGlobalHandlers = false;
1342         }
1343     }
1344 
1345     /**
1346      * Get the value of a logging property.
1347      * The method returns null if the property is not found.
1348      * @param name      property name
1349      * @return          property value
1350      */
1351     public String getProperty(String name) {
1352         return props.getProperty(name);
1353     }
1354 
1355     // Package private method to get a String property.
1356     // If the property is not defined we return the given
1357     // default value.


1603      * Returns <tt>LoggingMXBean</tt> for managing loggers.
1604      * An alternative way to manage loggers is through the
1605      * {@link java.lang.management.PlatformLoggingMXBean} interface
1606      * that can be obtained by calling:
1607      * <pre>
1608      *     PlatformLoggingMXBean logging = {@link java.lang.management.ManagementFactory#getPlatformMXBean(Class)
1609      *         ManagementFactory.getPlatformMXBean}(PlatformLoggingMXBean.class);
1610      * </pre>
1611      *
1612      * @return a {@link LoggingMXBean} object.
1613      *
1614      * @see java.lang.management.PlatformLoggingMXBean
1615      * @since 1.5
1616      */
1617     public static synchronized LoggingMXBean getLoggingMXBean() {
1618         if (loggingMXBean == null) {
1619             loggingMXBean =  new Logging();
1620         }
1621         return loggingMXBean;
1622     }
































































































1623 }
   1 /*
   2  * Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 
  27 package java.util.logging;
  28 
  29 import java.io.*;
  30 import java.util.*;
  31 import java.security.*;
  32 import java.lang.ref.ReferenceQueue;
  33 import java.lang.ref.WeakReference;
  34 import java.util.concurrent.CopyOnWriteArrayList;
  35 import sun.misc.JavaAWTAccess;
  36 import sun.misc.SharedSecrets;
  37 
  38 /**
  39  * There is a single global LogManager object that is used to
  40  * maintain a set of shared state about Loggers and log services.
  41  * <p>
  42  * This LogManager object:
  43  * <ul>
  44  * <li> Manages a hierarchical namespace of Logger objects.  All
  45  *      named Loggers are stored in this namespace.
  46  * <li> Manages a set of logging control properties.  These are
  47  *      simple key-value pairs that can be used by Handlers and
  48  *      other logging objects to configure themselves.
  49  * </ul>
  50  * <p>
  51  * The global LogManager object can be retrieved using LogManager.getLogManager().
  52  * The LogManager object is created during class initialization and
  53  * cannot subsequently be changed.
  54  * <p>


 153     private volatile Properties props = new Properties();
 154     private final static Level defaultLevel = Level.INFO;
 155 
 156     // LoggerContext for system loggers and user loggers
 157     private final LoggerContext systemContext = new SystemLoggerContext();
 158     private final LoggerContext userContext = new LoggerContext();
 159     // non final field - make it volatile to make sure that other threads
 160     // will see the new value once ensureLogManagerInitialized() has finished
 161     // executing.
 162     private volatile Logger rootLogger;
 163     // Have we done the primordial reading of the configuration file?
 164     // (Must be done after a suitable amount of java.lang.System
 165     // initialization has been done)
 166     private volatile boolean readPrimordialConfiguration;
 167     // Have we initialized global (root) handlers yet?
 168     // This gets set to false in readConfiguration
 169     private boolean initializedGlobalHandlers = true;
 170     // True if JVM death is imminent and the exit hook has been called.
 171     private boolean deathImminent;
 172 
 173     private final CopyOnWriteArrayList<ConfigurationListener> listeners =
 174             new CopyOnWriteArrayList<>();
 175 
 176     static {
 177         manager = AccessController.doPrivileged(new PrivilegedAction<LogManager>() {
 178             @Override
 179             public LogManager run() {
 180                 LogManager mgr = null;
 181                 String cname = null;
 182                 try {
 183                     cname = System.getProperty("java.util.logging.manager");
 184                     if (cname != null) {
 185                         try {
 186                             Class<?> clz = ClassLoader.getSystemClassLoader()
 187                                     .loadClass(cname);
 188                             mgr = (LogManager) clz.newInstance();
 189                         } catch (ClassNotFoundException ex) {
 190                             Class<?> clz = Thread.currentThread()
 191                                     .getContextClassLoader().loadClass(cname);
 192                             mgr = (LogManager) clz.newInstance();
 193                         }
 194                     }
 195                 } catch (Exception ex) {


1155      * return value from {@code LogManager.getLogger()} for null to properly
1156      * handle the case where the Logger has been garbage collected in the
1157      * time since its name was returned by this method.
1158      *
1159      * @return  enumeration of logger name strings
1160      */
1161     public Enumeration<String> getLoggerNames() {
1162         return getUserContext().getLoggerNames();
1163     }
1164 
1165     /**
1166      * Reinitialize the logging properties and reread the logging configuration.
1167      * <p>
1168      * The same rules are used for locating the configuration properties
1169      * as are used at startup.  So normally the logging properties will
1170      * be re-read from the same file that was used at startup.
1171      * <P>
1172      * Any log level definitions in the new configuration file will be
1173      * applied using Logger.setLevel(), if the target Logger exists.
1174      * <p>
1175      * The {@linkplain #addConfigurationListener(java.util.logging.LogManager.ConfigurationListener)
1176      * configuration listeners} will be invoked after the properties are read.
1177      *
1178      * @exception  SecurityException  if a security manager exists and if
1179      *             the caller does not have LoggingPermission("control").
1180      * @exception  IOException if there are IO problems reading the configuration.
1181      */
1182     public void readConfiguration() throws IOException, SecurityException {
1183         checkPermission();
1184 
1185         // if a configuration class is specified, load it and use it.
1186         String cname = System.getProperty("java.util.logging.config.class");
1187         if (cname != null) {
1188             try {
1189                 // Instantiate the named class.  It is its constructor's
1190                 // responsibility to initialize the logging configuration, by
1191                 // calling readConfiguration(InputStream) with a suitable stream.
1192                 try {
1193                     Class<?> clz = ClassLoader.getSystemClassLoader().loadClass(cname);
1194                     clz.newInstance();
1195                     return;
1196                 } catch (ClassNotFoundException ex) {


1290                 }
1291                 if (hands.charAt(end) == ',') {
1292                     break;
1293                 }
1294                 end++;
1295             }
1296             String word = hands.substring(ix, end);
1297             ix = end+1;
1298             word = word.trim();
1299             if (word.length() == 0) {
1300                 continue;
1301             }
1302             result.add(word);
1303         }
1304         return result.toArray(new String[result.size()]);
1305     }
1306 
1307     /**
1308      * Reinitialize the logging properties and reread the logging configuration
1309      * from the given stream, which should be in java.util.Properties format.
1310      * The {@linkplain #addConfigurationListener(java.util.logging.LogManager.ConfigurationListener)
1311      * configuration listeners} will be invoked after the properties are read.
1312      * <p>
1313      * Any log level definitions in the new configuration file will be
1314      * applied using Logger.setLevel(), if the target Logger exists.
1315      *
1316      * @param ins       stream to read properties from
1317      * @exception  SecurityException  if a security manager exists and if
1318      *             the caller does not have LoggingPermission("control").
1319      * @exception  IOException if there are problems reading from the stream.
1320      */
1321     public void readConfiguration(InputStream ins) throws IOException, SecurityException {
1322         checkPermission();
1323         reset();
1324 
1325         // Load the properties
1326         props.load(ins);
1327         // Instantiate new configuration objects.
1328         String names[] = parseClassNames("config");
1329 
1330         for (String word : names) {
1331             try {
1332                 Class<?> clz = ClassLoader.getSystemClassLoader().loadClass(word);
1333                 clz.newInstance();
1334             } catch (Exception ex) {
1335                 System.err.println("Can't load config class \"" + word + "\"");
1336                 System.err.println("" + ex);
1337                 // ex.printStackTrace();
1338             }
1339         }
1340 
1341         // Set levels on any pre-existing loggers, based on the new properties.
1342         setLevelsOnExistingLoggers();
1343 
1344         invokeConfigurationListeners();
1345 
1346         // Note that we need to reinitialize global handles when
1347         // they are first referenced.
1348         synchronized (this) {
1349             initializedGlobalHandlers = false;
1350         }
1351     }
1352 
1353     /**
1354      * Get the value of a logging property.
1355      * The method returns null if the property is not found.
1356      * @param name      property name
1357      * @return          property value
1358      */
1359     public String getProperty(String name) {
1360         return props.getProperty(name);
1361     }
1362 
1363     // Package private method to get a String property.
1364     // If the property is not defined we return the given
1365     // default value.


1611      * Returns <tt>LoggingMXBean</tt> for managing loggers.
1612      * An alternative way to manage loggers is through the
1613      * {@link java.lang.management.PlatformLoggingMXBean} interface
1614      * that can be obtained by calling:
1615      * <pre>
1616      *     PlatformLoggingMXBean logging = {@link java.lang.management.ManagementFactory#getPlatformMXBean(Class)
1617      *         ManagementFactory.getPlatformMXBean}(PlatformLoggingMXBean.class);
1618      * </pre>
1619      *
1620      * @return a {@link LoggingMXBean} object.
1621      *
1622      * @see java.lang.management.PlatformLoggingMXBean
1623      * @since 1.5
1624      */
1625     public static synchronized LoggingMXBean getLoggingMXBean() {
1626         if (loggingMXBean == null) {
1627             loggingMXBean =  new Logging();
1628         }
1629         return loggingMXBean;
1630     }
1631 
1632     /**
1633      * A configuration listener can be added to the LogManager in
1634      * in order to be informed of configuration loads.
1635      * When the LogManager reads (or re-reads) its configuration, it
1636      * will invoke all configuration listeners that are registered with it.
1637      *
1638      * @since 1.9
1639      */
1640     public static abstract class ConfigurationListener {
1641 
1642         private static Void checkPermission() {
1643             final SecurityManager sm = System.getSecurityManager();
1644             if (sm != null) {
1645                 sm.checkPermission(controlPermission);
1646             }
1647             return null;
1648         }
1649         protected ConfigurationListener() {
1650             this(checkPermission());
1651         }
1652         private ConfigurationListener(Void checked) {
1653         }
1654 
1655         /**
1656          * This method will be called by the LogManager when its configuration
1657          * has been read.
1658          * @see #readConfiguration(java.io.InputStream)
1659          */
1660         public abstract void configurationLoaded();
1661 
1662         @Override
1663         public final boolean equals(Object other) {
1664             return (other instanceof ConfigurationListener)
1665                     ? super.equals(other) : false;
1666         }
1667 
1668         @Override
1669         public final int hashCode() {
1670             return super.hashCode();
1671         }
1672 
1673     }
1674 
1675 
1676     /**
1677      * Adds a configuration listener to be invoked when the logging properties
1678      * are re-read and the configuration is changed.
1679      * Adding multiple instances of the same listener results in
1680      * the listener being invoked as many times as it was added when the
1681      * configuration is changed.
1682      *
1683      * @param listener A configuration listener that will be invoked after the
1684      *        configuration changed.
1685      * @throws SecurityException if a security manager exists and if the
1686      * caller does not have LoggingPermission("control").
1687      * @throws NullPointerException if the listener is null.
1688      *
1689      * @since 1.9
1690      */
1691     public void addConfigurationListener(ConfigurationListener listener) {
1692         ConfigurationListener l = Objects.requireNonNull(listener);
1693         checkPermission();
1694         listeners.add(l);
1695     }
1696 
1697     /**
1698      * Removes a previously registered configuration listener.
1699      * 
1700      * If the same listener instance has been added through multiple
1701      * invocations of {@code addConfigurationListener}, then an equivalent
1702      * number of {@code removeConfigurationListener} invocations are
1703      * required to remove all registration of that listener.
1704      * <P>
1705      * Returns silently if the given listener is {@code null} or is
1706      * not found.
1707      *
1708      * @param listener the configuration listener to remove (can be null)
1709      * @throws SecurityException if a security manager exists and if the
1710      * caller does not have LoggingPermission("control").
1711      *
1712      * @since 1.9
1713      */
1714     public void removeConfigurationListener(ConfigurationListener listener) {
1715         checkPermission();
1716         if (listener != null) {
1717             listeners.remove(listener);
1718         }
1719     }
1720 
1721     private void invokeConfigurationListeners() {
1722         for (ConfigurationListener listener : listeners) {
1723             listener.configurationLoaded();
1724         }
1725     }
1726 
1727 }