java.util.logging
public class: LogManager [javadoc |
source]
java.lang.Object
java.util.logging.LogManager
There is a single global LogManager object that is used to
maintain a set of shared state about Loggers and log services.
This LogManager object:
- Manages a hierarchical namespace of Logger objects. All
named Loggers are stored in this namespace.
- Manages a set of logging control properties. These are
simple key-value pairs that can be used by Handlers and
other logging objects to configure themselves.
The global LogManager object can be retrieved using LogManager.getLogManager().
The LogManager object is created during class initialization and
cannot subsequently be changed.
At startup the LogManager class is located using the
java.util.logging.manager system property.
By default, the LogManager reads its initial configuration from
a properties file "lib/logging.properties" in the JRE directory.
If you edit that property file you can change the default logging
configuration for all uses of that JRE.
In addition, the LogManager uses two optional system properties that
allow more control over reading the initial configuration:
- "java.util.logging.config.class"
- "java.util.logging.config.file"
These two properties may be set via the Preferences API, or as
command line property definitions to the "java" command, or as
system property definitions passed to JNI_CreateJavaVM.
If the "java.util.logging.config.class" property is set, then the
property value is treated as a class name. The given class will be
loaded, an object will be instantiated, and that object's constructor
is responsible for reading in the initial configuration. (That object
may use other system properties to control its configuration.) The
alternate configuration class can use readConfiguration(InputStream)
to define properties in the LogManager.
If "java.util.logging.config.class" property is not set,
then the "java.util.logging.config.file" system property can be used
to specify a properties file (in java.util.Properties format). The
initial logging configuration will be read from this file.
If neither of these properties is defined then, as described
above, the LogManager will read its initial configuration from
a properties file "lib/logging.properties" in the JRE directory.
The properties for loggers and Handlers will have names starting
with the dot-separated name for the handler or logger.
The global logging properties may include:
- A property "handlers". This defines a whitespace or comma separated
list of class names for handler classes to load and register as
handlers on the root Logger (the Logger named ""). Each class
name must be for a Handler class which has a default constructor.
Note that these Handlers may be created lazily, when they are
first used.
- A property "<logger>.handlers". This defines a whitespace or
comma separated list of class names for handlers classes to
load and register as handlers to the specified logger. Each class
name must be for a Handler class which has a default constructor.
Note that these Handlers may be created lazily, when they are
first used.
- A property "<logger>.useParentHandlers". This defines a boolean
value. By default every logger calls its parent in addition to
handling the logging message itself, this often result in messages
being handled by the root logger as well. When setting this property
to false a Handler needs to be configured for this logger otherwise
no logging messages are delivered.
- A property "config". This property is intended to allow
arbitrary configuration code to be run. The property defines a
whitespace or comma separated list of class names. A new instance will be
created for each named class. The default constructor of each class
may execute arbitrary code to update the logging configuration, such as
setting logger levels, adding handlers, adding filters, etc.
Note that all classes loaded during LogManager configuration are
first searched on the system class path before any user class path.
That includes the LogManager class, any config classes, and any
handler classes.
Loggers are organized into a naming hierarchy based on their
dot separated names. Thus "a.b.c" is a child of "a.b", but
"a.b1" and a.b2" are peers.
All properties whose names end with ".level" are assumed to define
log levels for Loggers. Thus "foo.level" defines a log level for
the logger called "foo" and (recursively) for any of its children
in the naming hierarchy. Log Levels are applied in the order they
are defined in the properties file. Thus level settings for child
nodes in the tree should come after settings for their parents.
The property name ".level" can be used to set the level for the
root of the tree.
All methods on the LogManager object are multi-thread safe.
| Field Summary |
|---|
| public static final String | LOGGING_MXBEAN_NAME | String representation of the
javax.management.ObjectName for LoggingMXBean . |
| Method from java.util.logging.LogManager Summary: |
|---|
|
addLogger, addPropertyChangeListener, checkAccess, demandLogger, getBooleanProperty, getFilterProperty, getFormatterProperty, getIntProperty, getLevelProperty, getLogManager, getLogger, getLoggerNames, getLoggingMXBean, getProperty, getStringProperty, readConfiguration, readConfiguration, removePropertyChangeListener, reset |
| Methods from java.lang.Object: |
|---|
|
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Method from java.util.logging.LogManager Detail: |
public synchronized boolean addLogger(Logger logger) {
final String name = logger.getName();
if (name == null) {
throw new NullPointerException();
}
WeakReference< Logger > ref = loggers.get(name);
if (ref != null) {
if (ref.get() == null) {
// Hashtable holds stale weak reference
// to a logger which has been GC-ed.
// Allow to register new one.
loggers.remove(name);
} else {
// We already have a registered logger with the given name.
return false;
}
}
// We're adding a new logger.
// Note that we are creating a weak reference here.
loggers.put(name, new WeakReference< Logger >(logger));
// Apply any initial level defined for the new logger.
Level level = getLevelProperty(name+".level", null);
if (level != null) {
doSetLevel(logger, level);
}
// Do we have a per logger handler too?
// Note: this will add a 200ms penalty
loadLoggerHandlers(logger, name, name+".handlers");
processParentHandlers(logger, name);
// Find the new node and its parent.
LogNode node = findNode(name);
node.loggerRef = new WeakReference< Logger >(logger);
Logger parent = null;
LogNode nodep = node.parent;
while (nodep != null) {
WeakReference< Logger > nodeRef = nodep.loggerRef;
if (nodeRef != null) {
parent = nodeRef.get();
if (parent != null) {
break;
}
}
nodep = nodep.parent;
}
if (parent != null) {
doSetParent(logger, parent);
}
// Walk over the children and tell them we are their new parent.
node.walkAndSetParent(logger);
return true;
}
Add a named logger. This does nothing and returns false if a logger
with the same name is already registered.
The Logger factory methods call this method to register each
newly created Logger.
The application should retain its own reference to the Logger
object to avoid it being garbage collected. The LogManager
may only retain a weak reference. |
public void addPropertyChangeListener(PropertyChangeListener l) throws SecurityException {
if (l == null) {
throw new NullPointerException();
}
checkAccess();
changes.addPropertyChangeListener(l);
}
Adds an event listener to be invoked when the logging
properties are re-read. Adding multiple instances of
the same event Listener results in multiple entries
in the property event listener table. |
public void checkAccess() throws SecurityException {
SecurityManager sm = System.getSecurityManager();
if (sm == null) {
return;
}
sm.checkPermission(ourPermission);
}
Check that the current context is trusted to modify the logging
configuration. This requires LoggingPermission("control").
If the check fails we throw a SecurityException, otherwise
we return normally. |
synchronized Logger demandLogger(String name) {
Logger result = getLogger(name);
if (result == null) {
result = new Logger(name, null);
addLogger(result);
result = getLogger(name);
}
return result;
}
|
boolean getBooleanProperty(String name,
boolean defaultValue) {
String val = getProperty(name);
if (val == null) {
return defaultValue;
}
val = val.toLowerCase();
if (val.equals("true") || val.equals("1")) {
return true;
} else if (val.equals("false") || val.equals("0")) {
return false;
}
return defaultValue;
}
|
Filter getFilterProperty(String name,
Filter defaultValue) {
String val = getProperty(name);
try {
if (val != null) {
Class clz = ClassLoader.getSystemClassLoader().loadClass(val);
return (Filter) clz.newInstance();
}
} catch (Exception ex) {
// We got one of a variety of exceptions in creating the
// class or creating an instance.
// Drop through.
}
// We got an exception. Return the defaultValue.
return defaultValue;
}
|
Formatter getFormatterProperty(String name,
Formatter defaultValue) {
String val = getProperty(name);
try {
if (val != null) {
Class clz = ClassLoader.getSystemClassLoader().loadClass(val);
return (Formatter) clz.newInstance();
}
} catch (Exception ex) {
// We got one of a variety of exceptions in creating the
// class or creating an instance.
// Drop through.
}
// We got an exception. Return the defaultValue.
return defaultValue;
}
|
int getIntProperty(String name,
int defaultValue) {
String val = getProperty(name);
if (val == null) {
return defaultValue;
}
try {
return Integer.parseInt(val.trim());
} catch (Exception ex) {
return defaultValue;
}
}
|
Level getLevelProperty(String name,
Level defaultValue) {
String val = getProperty(name);
if (val == null) {
return defaultValue;
}
try {
return Level.parse(val.trim());
} catch (Exception ex) {
return defaultValue;
}
}
|
public static LogManager getLogManager() {
if (manager != null) {
manager.readPrimordialConfiguration();
}
return manager;
}
Return the global LogManager object. |
public synchronized Logger getLogger(String name) {
WeakReference< Logger > ref = loggers.get(name);
if (ref == null) {
return null;
}
Logger logger = ref.get();
if (logger == null) {
// Hashtable holds stale weak reference
// to a logger which has been GC-ed.
loggers.remove(name);
}
return logger;
}
Method to find a named logger.
Note that since untrusted code may create loggers with
arbitrary names this method should not be relied on to
find Loggers for security sensitive logging.
|
public synchronized Enumeration getLoggerNames() {
return loggers.keys();
}
Get an enumeration of known logger names.
Note: Loggers may be added dynamically as new classes are loaded.
This method only reports on the loggers that are currently registered.
|
public static synchronized LoggingMXBean getLoggingMXBean() {
if (loggingMXBean == null) {
loggingMXBean = new Logging();
}
return loggingMXBean;
}
Returns LoggingMXBean for managing loggers.
The LoggingMXBean can also obtained from the
platform MBeanServer method. |
public String getProperty(String name) {
return props.getProperty(name);
}
Get the value of a logging property.
The method returns null if the property is not found. |
String getStringProperty(String name,
String defaultValue) {
String val = getProperty(name);
if (val == null) {
return defaultValue;
}
return val.trim();
}
|
public void readConfiguration() throws SecurityException, IOException {
checkAccess();
// if a configuration class is specified, load it and use it.
String cname = System.getProperty("java.util.logging.config.class");
if (cname != null) {
try {
// Instantiate the named class. It is its constructor's
// responsibility to initialize the logging configuration, by
// calling readConfiguration(InputStream) with a suitable stream.
try {
Class clz = ClassLoader.getSystemClassLoader().loadClass(cname);
clz.newInstance();
return;
} catch (ClassNotFoundException ex) {
Class clz = Thread.currentThread().getContextClassLoader().loadClass(cname);
clz.newInstance();
return;
}
} catch (Exception ex) {
System.err.println("Logging configuration class \"" + cname + "\" failed");
System.err.println("" + ex);
// keep going and useful config file.
}
}
String fname = System.getProperty("java.util.logging.config.file");
if (fname == null) {
fname = System.getProperty("java.home");
if (fname == null) {
throw new Error("Can't find java.home ??");
}
File f = new File(fname, "lib");
f = new File(f, "logging.properties");
fname = f.getCanonicalPath();
}
InputStream in = new FileInputStream(fname);
BufferedInputStream bin = new BufferedInputStream(in);
try {
readConfiguration(bin);
} finally {
if (in != null) {
in.close();
}
}
}
Reinitialize the logging properties and reread the logging configuration.
The same rules are used for locating the configuration properties
as are used at startup. So normally the logging properties will
be re-read from the same file that was used at startup.
Any log level definitions in the new configuration file will be
applied using Logger.setLevel(), if the target Logger exists.
A PropertyChangeEvent will be fired after the properties are read. |
public void readConfiguration(InputStream ins) throws SecurityException, IOException {
checkAccess();
reset();
// Load the properties
props.load(ins);
// Instantiate new configuration objects.
String names[] = parseClassNames("config");
for (int i = 0; i < names.length; i++) {
String word = names[i];
try {
Class clz = ClassLoader.getSystemClassLoader().loadClass(word);
clz.newInstance();
} catch (Exception ex) {
System.err.println("Can't load config class \"" + word + "\"");
System.err.println("" + ex);
// ex.printStackTrace();
}
}
// Set levels on any pre-existing loggers, based on the new properties.
setLevelsOnExistingLoggers();
// Notify any interested parties that our properties have changed.
changes.firePropertyChange(null, null, null);
// Note that we need to reinitialize global handles when
// they are first referenced.
synchronized (this) {
initializedGlobalHandlers = false;
}
}
Reinitialize the logging properties and reread the logging configuration
from the given stream, which should be in java.util.Properties format.
A PropertyChangeEvent will be fired after the properties are read.
Any log level definitions in the new configuration file will be
applied using Logger.setLevel(), if the target Logger exists. |
public void removePropertyChangeListener(PropertyChangeListener l) throws SecurityException {
checkAccess();
changes.removePropertyChangeListener(l);
}
|
public void reset() throws SecurityException {
checkAccess();
synchronized (this) {
props = new Properties();
// Since we are doing a reset we no longer want to initialize
// the global handlers, if they haven't been initialized yet.
initializedGlobalHandlers = true;
}
Enumeration enum_ = getLoggerNames();
while (enum_.hasMoreElements()) {
String name = (String)enum_.nextElement();
resetLogger(name);
}
}
Reset the logging configuration.
For all named loggers, the reset operation removes and closes
all Handlers and (except for the root logger) sets the level
to null. The root logger's level is set to Level.INFO. |