author | bae |
Wed, 04 Feb 2009 14:06:18 +0300 | |
changeset 2384 | b3ba5fb77f89 |
parent 2 | 90ce3da70b43 |
child 3319 | 53a6d815c92f |
permissions | -rw-r--r-- |
2 | 1 |
/* |
2 |
* Copyright 2000-2007 Sun Microsystems, Inc. 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. Sun designates this |
|
8 |
* particular file as subject to the "Classpath" exception as provided |
|
9 |
* by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, |
|
22 |
* CA 95054 USA or visit www.sun.com if you need additional information or |
|
23 |
* have any 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.WeakReference; |
|
33 |
import java.beans.PropertyChangeListener; |
|
34 |
import java.beans.PropertyChangeSupport; |
|
35 |
import java.net.URL; |
|
36 |
import sun.security.action.GetPropertyAction; |
|
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> |
|
55 |
* At startup the LogManager class is located using the |
|
56 |
* java.util.logging.manager system property. |
|
57 |
* <p> |
|
58 |
* By default, the LogManager reads its initial configuration from |
|
59 |
* a properties file "lib/logging.properties" in the JRE directory. |
|
60 |
* If you edit that property file you can change the default logging |
|
61 |
* configuration for all uses of that JRE. |
|
62 |
* <p> |
|
63 |
* In addition, the LogManager uses two optional system properties that |
|
64 |
* allow more control over reading the initial configuration: |
|
65 |
* <ul> |
|
66 |
* <li>"java.util.logging.config.class" |
|
67 |
* <li>"java.util.logging.config.file" |
|
68 |
* </ul> |
|
69 |
* These two properties may be set via the Preferences API, or as |
|
70 |
* command line property definitions to the "java" command, or as |
|
71 |
* system property definitions passed to JNI_CreateJavaVM. |
|
72 |
* <p> |
|
73 |
* If the "java.util.logging.config.class" property is set, then the |
|
74 |
* property value is treated as a class name. The given class will be |
|
75 |
* loaded, an object will be instantiated, and that object's constructor |
|
76 |
* is responsible for reading in the initial configuration. (That object |
|
77 |
* may use other system properties to control its configuration.) The |
|
78 |
* alternate configuration class can use <tt>readConfiguration(InputStream)</tt> |
|
79 |
* to define properties in the LogManager. |
|
80 |
* <p> |
|
81 |
* If "java.util.logging.config.class" property is <b>not</b> set, |
|
82 |
* then the "java.util.logging.config.file" system property can be used |
|
83 |
* to specify a properties file (in java.util.Properties format). The |
|
84 |
* initial logging configuration will be read from this file. |
|
85 |
* <p> |
|
86 |
* If neither of these properties is defined then, as described |
|
87 |
* above, the LogManager will read its initial configuration from |
|
88 |
* a properties file "lib/logging.properties" in the JRE directory. |
|
89 |
* <p> |
|
90 |
* The properties for loggers and Handlers will have names starting |
|
91 |
* with the dot-separated name for the handler or logger. |
|
92 |
* <p> |
|
93 |
* The global logging properties may include: |
|
94 |
* <ul> |
|
95 |
* <li>A property "handlers". This defines a whitespace or comma separated |
|
96 |
* list of class names for handler classes to load and register as |
|
97 |
* handlers on the root Logger (the Logger named ""). Each class |
|
98 |
* name must be for a Handler class which has a default constructor. |
|
99 |
* Note that these Handlers may be created lazily, when they are |
|
100 |
* first used. |
|
101 |
* |
|
102 |
* <li>A property "<logger>.handlers". This defines a whitespace or |
|
103 |
* comma separated list of class names for handlers classes to |
|
104 |
* load and register as handlers to the specified logger. Each class |
|
105 |
* name must be for a Handler class which has a default constructor. |
|
106 |
* Note that these Handlers may be created lazily, when they are |
|
107 |
* first used. |
|
108 |
* |
|
109 |
* <li>A property "<logger>.useParentHandlers". This defines a boolean |
|
110 |
* value. By default every logger calls its parent in addition to |
|
111 |
* handling the logging message itself, this often result in messages |
|
112 |
* being handled by the root logger as well. When setting this property |
|
113 |
* to false a Handler needs to be configured for this logger otherwise |
|
114 |
* no logging messages are delivered. |
|
115 |
* |
|
116 |
* <li>A property "config". This property is intended to allow |
|
117 |
* arbitrary configuration code to be run. The property defines a |
|
118 |
* whitespace or comma separated list of class names. A new instance will be |
|
119 |
* created for each named class. The default constructor of each class |
|
120 |
* may execute arbitrary code to update the logging configuration, such as |
|
121 |
* setting logger levels, adding handlers, adding filters, etc. |
|
122 |
* </ul> |
|
123 |
* <p> |
|
124 |
* Note that all classes loaded during LogManager configuration are |
|
125 |
* first searched on the system class path before any user class path. |
|
126 |
* That includes the LogManager class, any config classes, and any |
|
127 |
* handler classes. |
|
128 |
* <p> |
|
129 |
* Loggers are organized into a naming hierarchy based on their |
|
130 |
* dot separated names. Thus "a.b.c" is a child of "a.b", but |
|
131 |
* "a.b1" and a.b2" are peers. |
|
132 |
* <p> |
|
133 |
* All properties whose names end with ".level" are assumed to define |
|
134 |
* log levels for Loggers. Thus "foo.level" defines a log level for |
|
135 |
* the logger called "foo" and (recursively) for any of its children |
|
136 |
* in the naming hierarchy. Log Levels are applied in the order they |
|
137 |
* are defined in the properties file. Thus level settings for child |
|
138 |
* nodes in the tree should come after settings for their parents. |
|
139 |
* The property name ".level" can be used to set the level for the |
|
140 |
* root of the tree. |
|
141 |
* <p> |
|
142 |
* All methods on the LogManager object are multi-thread safe. |
|
143 |
* |
|
144 |
* @since 1.4 |
|
145 |
*/ |
|
146 |
||
147 |
public class LogManager { |
|
148 |
// The global LogManager object |
|
149 |
private static LogManager manager; |
|
150 |
||
151 |
private final static Handler[] emptyHandlers = { }; |
|
152 |
private Properties props = new Properties(); |
|
153 |
private PropertyChangeSupport changes |
|
154 |
= new PropertyChangeSupport(LogManager.class); |
|
155 |
private final static Level defaultLevel = Level.INFO; |
|
156 |
||
157 |
// Table of known loggers. Maps names to Loggers. |
|
158 |
private Hashtable<String,WeakReference<Logger>> loggers = |
|
159 |
new Hashtable<String,WeakReference<Logger>>(); |
|
160 |
// Tree of known loggers |
|
161 |
private LogNode root = new LogNode(null); |
|
162 |
private Logger rootLogger; |
|
163 |
||
164 |
// Have we done the primordial reading of the configuration file? |
|
165 |
// (Must be done after a suitable amount of java.lang.System |
|
166 |
// initialization has been done) |
|
167 |
private volatile boolean readPrimordialConfiguration; |
|
168 |
// Have we initialized global (root) handlers yet? |
|
169 |
// This gets set to false in readConfiguration |
|
170 |
private boolean initializedGlobalHandlers = true; |
|
171 |
// True if JVM death is imminent and the exit hook has been called. |
|
172 |
private boolean deathImminent; |
|
173 |
||
174 |
static { |
|
175 |
AccessController.doPrivileged(new PrivilegedAction<Object>() { |
|
176 |
public Object run() { |
|
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().loadClass(cname); |
|
183 |
manager = (LogManager) clz.newInstance(); |
|
184 |
} catch (ClassNotFoundException ex) { |
|
185 |
Class clz = Thread.currentThread().getContextClassLoader().loadClass(cname); |
|
186 |
manager = (LogManager) clz.newInstance(); |
|
187 |
} |
|
188 |
} |
|
189 |
} catch (Exception ex) { |
|
190 |
System.err.println("Could not load Logmanager \"" + cname + "\""); |
|
191 |
ex.printStackTrace(); |
|
192 |
} |
|
193 |
if (manager == null) { |
|
194 |
manager = new LogManager(); |
|
195 |
} |
|
196 |
||
197 |
// Create and retain Logger for the root of the namespace. |
|
198 |
manager.rootLogger = manager.new RootLogger(); |
|
199 |
manager.addLogger(manager.rootLogger); |
|
200 |
||
201 |
// Adding the global Logger. Doing so in the Logger.<clinit> |
|
202 |
// would deadlock with the LogManager.<clinit>. |
|
203 |
Logger.global.setLogManager(manager); |
|
204 |
manager.addLogger(Logger.global); |
|
205 |
||
206 |
// We don't call readConfiguration() here, as we may be running |
|
207 |
// very early in the JVM startup sequence. Instead readConfiguration |
|
208 |
// will be called lazily in getLogManager(). |
|
209 |
return null; |
|
210 |
} |
|
211 |
}); |
|
212 |
} |
|
213 |
||
214 |
||
215 |
// This private class is used as a shutdown hook. |
|
216 |
// It does a "reset" to close all open handlers. |
|
217 |
private class Cleaner extends Thread { |
|
2384
b3ba5fb77f89
6799583: LogManager shutdown hook may cause a memory leak.
bae
parents:
2
diff
changeset
|
218 |
|
b3ba5fb77f89
6799583: LogManager shutdown hook may cause a memory leak.
bae
parents:
2
diff
changeset
|
219 |
private Cleaner() { |
b3ba5fb77f89
6799583: LogManager shutdown hook may cause a memory leak.
bae
parents:
2
diff
changeset
|
220 |
/* Set context class loader to null in order to avoid |
b3ba5fb77f89
6799583: LogManager shutdown hook may cause a memory leak.
bae
parents:
2
diff
changeset
|
221 |
* keeping a strong reference to an application classloader. |
b3ba5fb77f89
6799583: LogManager shutdown hook may cause a memory leak.
bae
parents:
2
diff
changeset
|
222 |
*/ |
b3ba5fb77f89
6799583: LogManager shutdown hook may cause a memory leak.
bae
parents:
2
diff
changeset
|
223 |
this.setContextClassLoader(null); |
b3ba5fb77f89
6799583: LogManager shutdown hook may cause a memory leak.
bae
parents:
2
diff
changeset
|
224 |
} |
b3ba5fb77f89
6799583: LogManager shutdown hook may cause a memory leak.
bae
parents:
2
diff
changeset
|
225 |
|
2 | 226 |
public void run() { |
227 |
// This is to ensure the LogManager.<clinit> is completed |
|
228 |
// before synchronized block. Otherwise deadlocks are possible. |
|
229 |
LogManager mgr = manager; |
|
230 |
||
231 |
// If the global handlers haven't been initialized yet, we |
|
232 |
// don't want to initialize them just so we can close them! |
|
233 |
synchronized (LogManager.this) { |
|
234 |
// Note that death is imminent. |
|
235 |
deathImminent = true; |
|
236 |
initializedGlobalHandlers = true; |
|
237 |
} |
|
238 |
||
239 |
// Do a reset to close all active handlers. |
|
240 |
reset(); |
|
241 |
} |
|
242 |
} |
|
243 |
||
244 |
||
245 |
/** |
|
246 |
* Protected constructor. This is protected so that container applications |
|
247 |
* (such as J2EE containers) can subclass the object. It is non-public as |
|
248 |
* it is intended that there only be one LogManager object, whose value is |
|
249 |
* retrieved by calling Logmanager.getLogManager. |
|
250 |
*/ |
|
251 |
protected LogManager() { |
|
252 |
// Add a shutdown hook to close the global handlers. |
|
253 |
try { |
|
254 |
Runtime.getRuntime().addShutdownHook(new Cleaner()); |
|
255 |
} catch (IllegalStateException e) { |
|
256 |
// If the VM is already shutting down, |
|
257 |
// We do not need to register shutdownHook. |
|
258 |
} |
|
259 |
} |
|
260 |
||
261 |
/** |
|
262 |
* Return the global LogManager object. |
|
263 |
*/ |
|
264 |
public static LogManager getLogManager() { |
|
265 |
if (manager != null) { |
|
266 |
manager.readPrimordialConfiguration(); |
|
267 |
} |
|
268 |
return manager; |
|
269 |
} |
|
270 |
||
271 |
private void readPrimordialConfiguration() { |
|
272 |
if (!readPrimordialConfiguration) { |
|
273 |
synchronized (this) { |
|
274 |
if (!readPrimordialConfiguration) { |
|
275 |
// If System.in/out/err are null, it's a good |
|
276 |
// indication that we're still in the |
|
277 |
// bootstrapping phase |
|
278 |
if (System.out == null) { |
|
279 |
return; |
|
280 |
} |
|
281 |
readPrimordialConfiguration = true; |
|
282 |
try { |
|
283 |
AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { |
|
284 |
public Object run() throws Exception { |
|
285 |
readConfiguration(); |
|
286 |
return null; |
|
287 |
} |
|
288 |
}); |
|
289 |
} catch (Exception ex) { |
|
290 |
// System.err.println("Can't read logging configuration:"); |
|
291 |
// ex.printStackTrace(); |
|
292 |
} |
|
293 |
} |
|
294 |
} |
|
295 |
} |
|
296 |
} |
|
297 |
||
298 |
/** |
|
299 |
* Adds an event listener to be invoked when the logging |
|
300 |
* properties are re-read. Adding multiple instances of |
|
301 |
* the same event Listener results in multiple entries |
|
302 |
* in the property event listener table. |
|
303 |
* |
|
304 |
* @param l event listener |
|
305 |
* @exception SecurityException if a security manager exists and if |
|
306 |
* the caller does not have LoggingPermission("control"). |
|
307 |
* @exception NullPointerException if the PropertyChangeListener is null. |
|
308 |
*/ |
|
309 |
public void addPropertyChangeListener(PropertyChangeListener l) throws SecurityException { |
|
310 |
if (l == null) { |
|
311 |
throw new NullPointerException(); |
|
312 |
} |
|
313 |
checkAccess(); |
|
314 |
changes.addPropertyChangeListener(l); |
|
315 |
} |
|
316 |
||
317 |
/** |
|
318 |
* Removes an event listener for property change events. |
|
319 |
* If the same listener instance has been added to the listener table |
|
320 |
* through multiple invocations of <CODE>addPropertyChangeListener</CODE>, |
|
321 |
* then an equivalent number of |
|
322 |
* <CODE>removePropertyChangeListener</CODE> invocations are required to remove |
|
323 |
* all instances of that listener from the listener table. |
|
324 |
* <P> |
|
325 |
* Returns silently if the given listener is not found. |
|
326 |
* |
|
327 |
* @param l event listener (can be null) |
|
328 |
* @exception SecurityException if a security manager exists and if |
|
329 |
* the caller does not have LoggingPermission("control"). |
|
330 |
*/ |
|
331 |
public void removePropertyChangeListener(PropertyChangeListener l) throws SecurityException { |
|
332 |
checkAccess(); |
|
333 |
changes.removePropertyChangeListener(l); |
|
334 |
} |
|
335 |
||
336 |
// Package-level method. |
|
337 |
// Find or create a specified logger instance. If a logger has |
|
338 |
// already been created with the given name it is returned. |
|
339 |
// Otherwise a new logger instance is created and registered |
|
340 |
// in the LogManager global namespace. |
|
341 |
synchronized Logger demandLogger(String name) { |
|
342 |
Logger result = getLogger(name); |
|
343 |
if (result == null) { |
|
344 |
result = new Logger(name, null); |
|
345 |
addLogger(result); |
|
346 |
result = getLogger(name); |
|
347 |
} |
|
348 |
return result; |
|
349 |
} |
|
350 |
||
351 |
// If logger.getUseParentHandlers() returns 'true' and any of the logger's |
|
352 |
// parents have levels or handlers defined, make sure they are instantiated. |
|
353 |
private void processParentHandlers(Logger logger, String name) { |
|
354 |
int ix = 1; |
|
355 |
for (;;) { |
|
356 |
int ix2 = name.indexOf(".", ix); |
|
357 |
if (ix2 < 0) { |
|
358 |
break; |
|
359 |
} |
|
360 |
String pname = name.substring(0,ix2); |
|
361 |
||
362 |
if (getProperty(pname+".level") != null || |
|
363 |
getProperty(pname+".handlers") != null) { |
|
364 |
// This pname has a level/handlers definition. |
|
365 |
// Make sure it exists. |
|
366 |
demandLogger(pname); |
|
367 |
} |
|
368 |
ix = ix2+1; |
|
369 |
} |
|
370 |
} |
|
371 |
||
372 |
// Add new per logger handlers. |
|
373 |
// We need to raise privilege here. All our decisions will |
|
374 |
// be made based on the logging configuration, which can |
|
375 |
// only be modified by trusted code. |
|
376 |
private void loadLoggerHandlers(final Logger logger, final String name, |
|
377 |
final String handlersPropertyName) { |
|
378 |
AccessController.doPrivileged(new PrivilegedAction<Object>() { |
|
379 |
public Object run() { |
|
380 |
if (logger != rootLogger) { |
|
381 |
boolean useParent = getBooleanProperty(name + ".useParentHandlers", true); |
|
382 |
if (!useParent) { |
|
383 |
logger.setUseParentHandlers(false); |
|
384 |
} |
|
385 |
} |
|
386 |
||
387 |
String names[] = parseClassNames(handlersPropertyName); |
|
388 |
for (int i = 0; i < names.length; i++) { |
|
389 |
String word = names[i]; |
|
390 |
try { |
|
391 |
Class clz = ClassLoader.getSystemClassLoader().loadClass(word); |
|
392 |
Handler hdl = (Handler) clz.newInstance(); |
|
393 |
try { |
|
394 |
// Check if there is a property defining the |
|
395 |
// this handler's level. |
|
396 |
String levs = getProperty(word + ".level"); |
|
397 |
if (levs != null) { |
|
398 |
hdl.setLevel(Level.parse(levs)); |
|
399 |
} |
|
400 |
} catch (Exception ex) { |
|
401 |
System.err.println("Can't set level for " + word); |
|
402 |
// Probably a bad level. Drop through. |
|
403 |
} |
|
404 |
// Add this Handler to the logger |
|
405 |
logger.addHandler(hdl); |
|
406 |
} catch (Exception ex) { |
|
407 |
System.err.println("Can't load log handler \"" + word + "\""); |
|
408 |
System.err.println("" + ex); |
|
409 |
ex.printStackTrace(); |
|
410 |
} |
|
411 |
} |
|
412 |
return null; |
|
413 |
}}); |
|
414 |
} |
|
415 |
||
416 |
/** |
|
417 |
* Add a named logger. This does nothing and returns false if a logger |
|
418 |
* with the same name is already registered. |
|
419 |
* <p> |
|
420 |
* The Logger factory methods call this method to register each |
|
421 |
* newly created Logger. |
|
422 |
* <p> |
|
423 |
* The application should retain its own reference to the Logger |
|
424 |
* object to avoid it being garbage collected. The LogManager |
|
425 |
* may only retain a weak reference. |
|
426 |
* |
|
427 |
* @param logger the new logger. |
|
428 |
* @return true if the argument logger was registered successfully, |
|
429 |
* false if a logger of that name already exists. |
|
430 |
* @exception NullPointerException if the logger name is null. |
|
431 |
*/ |
|
432 |
public synchronized boolean addLogger(Logger logger) { |
|
433 |
final String name = logger.getName(); |
|
434 |
if (name == null) { |
|
435 |
throw new NullPointerException(); |
|
436 |
} |
|
437 |
||
438 |
WeakReference<Logger> ref = loggers.get(name); |
|
439 |
if (ref != null) { |
|
440 |
if (ref.get() == null) { |
|
441 |
// Hashtable holds stale weak reference |
|
442 |
// to a logger which has been GC-ed. |
|
443 |
// Allow to register new one. |
|
444 |
loggers.remove(name); |
|
445 |
} else { |
|
446 |
// We already have a registered logger with the given name. |
|
447 |
return false; |
|
448 |
} |
|
449 |
} |
|
450 |
||
451 |
// We're adding a new logger. |
|
452 |
// Note that we are creating a weak reference here. |
|
453 |
loggers.put(name, new WeakReference<Logger>(logger)); |
|
454 |
||
455 |
// Apply any initial level defined for the new logger. |
|
456 |
Level level = getLevelProperty(name+".level", null); |
|
457 |
if (level != null) { |
|
458 |
doSetLevel(logger, level); |
|
459 |
} |
|
460 |
||
461 |
// Do we have a per logger handler too? |
|
462 |
// Note: this will add a 200ms penalty |
|
463 |
loadLoggerHandlers(logger, name, name+".handlers"); |
|
464 |
processParentHandlers(logger, name); |
|
465 |
||
466 |
// Find the new node and its parent. |
|
467 |
LogNode node = findNode(name); |
|
468 |
node.loggerRef = new WeakReference<Logger>(logger); |
|
469 |
Logger parent = null; |
|
470 |
LogNode nodep = node.parent; |
|
471 |
while (nodep != null) { |
|
472 |
WeakReference<Logger> nodeRef = nodep.loggerRef; |
|
473 |
if (nodeRef != null) { |
|
474 |
parent = nodeRef.get(); |
|
475 |
if (parent != null) { |
|
476 |
break; |
|
477 |
} |
|
478 |
} |
|
479 |
nodep = nodep.parent; |
|
480 |
} |
|
481 |
||
482 |
if (parent != null) { |
|
483 |
doSetParent(logger, parent); |
|
484 |
} |
|
485 |
// Walk over the children and tell them we are their new parent. |
|
486 |
node.walkAndSetParent(logger); |
|
487 |
||
488 |
return true; |
|
489 |
} |
|
490 |
||
491 |
||
492 |
// Private method to set a level on a logger. |
|
493 |
// If necessary, we raise privilege before doing the call. |
|
494 |
private static void doSetLevel(final Logger logger, final Level level) { |
|
495 |
SecurityManager sm = System.getSecurityManager(); |
|
496 |
if (sm == null) { |
|
497 |
// There is no security manager, so things are easy. |
|
498 |
logger.setLevel(level); |
|
499 |
return; |
|
500 |
} |
|
501 |
// There is a security manager. Raise privilege before |
|
502 |
// calling setLevel. |
|
503 |
AccessController.doPrivileged(new PrivilegedAction<Object>() { |
|
504 |
public Object run() { |
|
505 |
logger.setLevel(level); |
|
506 |
return null; |
|
507 |
}}); |
|
508 |
} |
|
509 |
||
510 |
||
511 |
||
512 |
// Private method to set a parent on a logger. |
|
513 |
// If necessary, we raise privilege before doing the setParent call. |
|
514 |
private static void doSetParent(final Logger logger, final Logger parent) { |
|
515 |
SecurityManager sm = System.getSecurityManager(); |
|
516 |
if (sm == null) { |
|
517 |
// There is no security manager, so things are easy. |
|
518 |
logger.setParent(parent); |
|
519 |
return; |
|
520 |
} |
|
521 |
// There is a security manager. Raise privilege before |
|
522 |
// calling setParent. |
|
523 |
AccessController.doPrivileged(new PrivilegedAction<Object>() { |
|
524 |
public Object run() { |
|
525 |
logger.setParent(parent); |
|
526 |
return null; |
|
527 |
}}); |
|
528 |
} |
|
529 |
||
530 |
// Find a node in our tree of logger nodes. |
|
531 |
// If necessary, create it. |
|
532 |
private LogNode findNode(String name) { |
|
533 |
if (name == null || name.equals("")) { |
|
534 |
return root; |
|
535 |
} |
|
536 |
LogNode node = root; |
|
537 |
while (name.length() > 0) { |
|
538 |
int ix = name.indexOf("."); |
|
539 |
String head; |
|
540 |
if (ix > 0) { |
|
541 |
head = name.substring(0,ix); |
|
542 |
name = name.substring(ix+1); |
|
543 |
} else { |
|
544 |
head = name; |
|
545 |
name = ""; |
|
546 |
} |
|
547 |
if (node.children == null) { |
|
548 |
node.children = new HashMap<String,LogNode>(); |
|
549 |
} |
|
550 |
LogNode child = node.children.get(head); |
|
551 |
if (child == null) { |
|
552 |
child = new LogNode(node); |
|
553 |
node.children.put(head, child); |
|
554 |
} |
|
555 |
node = child; |
|
556 |
} |
|
557 |
return node; |
|
558 |
} |
|
559 |
||
560 |
/** |
|
561 |
* Method to find a named logger. |
|
562 |
* <p> |
|
563 |
* Note that since untrusted code may create loggers with |
|
564 |
* arbitrary names this method should not be relied on to |
|
565 |
* find Loggers for security sensitive logging. |
|
566 |
* <p> |
|
567 |
* @param name name of the logger |
|
568 |
* @return matching logger or null if none is found |
|
569 |
*/ |
|
570 |
public synchronized Logger getLogger(String name) { |
|
571 |
WeakReference<Logger> ref = loggers.get(name); |
|
572 |
if (ref == null) { |
|
573 |
return null; |
|
574 |
} |
|
575 |
Logger logger = ref.get(); |
|
576 |
if (logger == null) { |
|
577 |
// Hashtable holds stale weak reference |
|
578 |
// to a logger which has been GC-ed. |
|
579 |
loggers.remove(name); |
|
580 |
} |
|
581 |
return logger; |
|
582 |
} |
|
583 |
||
584 |
/** |
|
585 |
* Get an enumeration of known logger names. |
|
586 |
* <p> |
|
587 |
* Note: Loggers may be added dynamically as new classes are loaded. |
|
588 |
* This method only reports on the loggers that are currently registered. |
|
589 |
* <p> |
|
590 |
* @return enumeration of logger name strings |
|
591 |
*/ |
|
592 |
public synchronized Enumeration<String> getLoggerNames() { |
|
593 |
return loggers.keys(); |
|
594 |
} |
|
595 |
||
596 |
/** |
|
597 |
* Reinitialize the logging properties and reread the logging configuration. |
|
598 |
* <p> |
|
599 |
* The same rules are used for locating the configuration properties |
|
600 |
* as are used at startup. So normally the logging properties will |
|
601 |
* be re-read from the same file that was used at startup. |
|
602 |
* <P> |
|
603 |
* Any log level definitions in the new configuration file will be |
|
604 |
* applied using Logger.setLevel(), if the target Logger exists. |
|
605 |
* <p> |
|
606 |
* A PropertyChangeEvent will be fired after the properties are read. |
|
607 |
* |
|
608 |
* @exception SecurityException if a security manager exists and if |
|
609 |
* the caller does not have LoggingPermission("control"). |
|
610 |
* @exception IOException if there are IO problems reading the configuration. |
|
611 |
*/ |
|
612 |
public void readConfiguration() throws IOException, SecurityException { |
|
613 |
checkAccess(); |
|
614 |
||
615 |
// if a configuration class is specified, load it and use it. |
|
616 |
String cname = System.getProperty("java.util.logging.config.class"); |
|
617 |
if (cname != null) { |
|
618 |
try { |
|
619 |
// Instantiate the named class. It is its constructor's |
|
620 |
// responsibility to initialize the logging configuration, by |
|
621 |
// calling readConfiguration(InputStream) with a suitable stream. |
|
622 |
try { |
|
623 |
Class clz = ClassLoader.getSystemClassLoader().loadClass(cname); |
|
624 |
clz.newInstance(); |
|
625 |
return; |
|
626 |
} catch (ClassNotFoundException ex) { |
|
627 |
Class clz = Thread.currentThread().getContextClassLoader().loadClass(cname); |
|
628 |
clz.newInstance(); |
|
629 |
return; |
|
630 |
} |
|
631 |
} catch (Exception ex) { |
|
632 |
System.err.println("Logging configuration class \"" + cname + "\" failed"); |
|
633 |
System.err.println("" + ex); |
|
634 |
// keep going and useful config file. |
|
635 |
} |
|
636 |
} |
|
637 |
||
638 |
String fname = System.getProperty("java.util.logging.config.file"); |
|
639 |
if (fname == null) { |
|
640 |
fname = System.getProperty("java.home"); |
|
641 |
if (fname == null) { |
|
642 |
throw new Error("Can't find java.home ??"); |
|
643 |
} |
|
644 |
File f = new File(fname, "lib"); |
|
645 |
f = new File(f, "logging.properties"); |
|
646 |
fname = f.getCanonicalPath(); |
|
647 |
} |
|
648 |
InputStream in = new FileInputStream(fname); |
|
649 |
BufferedInputStream bin = new BufferedInputStream(in); |
|
650 |
try { |
|
651 |
readConfiguration(bin); |
|
652 |
} finally { |
|
653 |
if (in != null) { |
|
654 |
in.close(); |
|
655 |
} |
|
656 |
} |
|
657 |
} |
|
658 |
||
659 |
/** |
|
660 |
* Reset the logging configuration. |
|
661 |
* <p> |
|
662 |
* For all named loggers, the reset operation removes and closes |
|
663 |
* all Handlers and (except for the root logger) sets the level |
|
664 |
* to null. The root logger's level is set to Level.INFO. |
|
665 |
* |
|
666 |
* @exception SecurityException if a security manager exists and if |
|
667 |
* the caller does not have LoggingPermission("control"). |
|
668 |
*/ |
|
669 |
||
670 |
public void reset() throws SecurityException { |
|
671 |
checkAccess(); |
|
672 |
synchronized (this) { |
|
673 |
props = new Properties(); |
|
674 |
// Since we are doing a reset we no longer want to initialize |
|
675 |
// the global handlers, if they haven't been initialized yet. |
|
676 |
initializedGlobalHandlers = true; |
|
677 |
} |
|
678 |
Enumeration enum_ = getLoggerNames(); |
|
679 |
while (enum_.hasMoreElements()) { |
|
680 |
String name = (String)enum_.nextElement(); |
|
681 |
resetLogger(name); |
|
682 |
} |
|
683 |
} |
|
684 |
||
685 |
||
686 |
// Private method to reset an individual target logger. |
|
687 |
private void resetLogger(String name) { |
|
688 |
Logger logger = getLogger(name); |
|
689 |
if (logger == null) { |
|
690 |
return; |
|
691 |
} |
|
692 |
// Close all the Logger's handlers. |
|
693 |
Handler[] targets = logger.getHandlers(); |
|
694 |
for (int i = 0; i < targets.length; i++) { |
|
695 |
Handler h = targets[i]; |
|
696 |
logger.removeHandler(h); |
|
697 |
try { |
|
698 |
h.close(); |
|
699 |
} catch (Exception ex) { |
|
700 |
// Problems closing a handler? Keep going... |
|
701 |
} |
|
702 |
} |
|
703 |
if (name != null && name.equals("")) { |
|
704 |
// This is the root logger. |
|
705 |
logger.setLevel(defaultLevel); |
|
706 |
} else { |
|
707 |
logger.setLevel(null); |
|
708 |
} |
|
709 |
} |
|
710 |
||
711 |
// get a list of whitespace separated classnames from a property. |
|
712 |
private String[] parseClassNames(String propertyName) { |
|
713 |
String hands = getProperty(propertyName); |
|
714 |
if (hands == null) { |
|
715 |
return new String[0]; |
|
716 |
} |
|
717 |
hands = hands.trim(); |
|
718 |
int ix = 0; |
|
719 |
Vector<String> result = new Vector<String>(); |
|
720 |
while (ix < hands.length()) { |
|
721 |
int end = ix; |
|
722 |
while (end < hands.length()) { |
|
723 |
if (Character.isWhitespace(hands.charAt(end))) { |
|
724 |
break; |
|
725 |
} |
|
726 |
if (hands.charAt(end) == ',') { |
|
727 |
break; |
|
728 |
} |
|
729 |
end++; |
|
730 |
} |
|
731 |
String word = hands.substring(ix, end); |
|
732 |
ix = end+1; |
|
733 |
word = word.trim(); |
|
734 |
if (word.length() == 0) { |
|
735 |
continue; |
|
736 |
} |
|
737 |
result.add(word); |
|
738 |
} |
|
739 |
return result.toArray(new String[result.size()]); |
|
740 |
} |
|
741 |
||
742 |
/** |
|
743 |
* Reinitialize the logging properties and reread the logging configuration |
|
744 |
* from the given stream, which should be in java.util.Properties format. |
|
745 |
* A PropertyChangeEvent will be fired after the properties are read. |
|
746 |
* <p> |
|
747 |
* Any log level definitions in the new configuration file will be |
|
748 |
* applied using Logger.setLevel(), if the target Logger exists. |
|
749 |
* |
|
750 |
* @param ins stream to read properties from |
|
751 |
* @exception SecurityException if a security manager exists and if |
|
752 |
* the caller does not have LoggingPermission("control"). |
|
753 |
* @exception IOException if there are problems reading from the stream. |
|
754 |
*/ |
|
755 |
public void readConfiguration(InputStream ins) throws IOException, SecurityException { |
|
756 |
checkAccess(); |
|
757 |
reset(); |
|
758 |
||
759 |
// Load the properties |
|
760 |
props.load(ins); |
|
761 |
// Instantiate new configuration objects. |
|
762 |
String names[] = parseClassNames("config"); |
|
763 |
||
764 |
for (int i = 0; i < names.length; i++) { |
|
765 |
String word = names[i]; |
|
766 |
try { |
|
767 |
Class clz = ClassLoader.getSystemClassLoader().loadClass(word); |
|
768 |
clz.newInstance(); |
|
769 |
} catch (Exception ex) { |
|
770 |
System.err.println("Can't load config class \"" + word + "\""); |
|
771 |
System.err.println("" + ex); |
|
772 |
// ex.printStackTrace(); |
|
773 |
} |
|
774 |
} |
|
775 |
||
776 |
// Set levels on any pre-existing loggers, based on the new properties. |
|
777 |
setLevelsOnExistingLoggers(); |
|
778 |
||
779 |
// Notify any interested parties that our properties have changed. |
|
780 |
changes.firePropertyChange(null, null, null); |
|
781 |
||
782 |
// Note that we need to reinitialize global handles when |
|
783 |
// they are first referenced. |
|
784 |
synchronized (this) { |
|
785 |
initializedGlobalHandlers = false; |
|
786 |
} |
|
787 |
} |
|
788 |
||
789 |
/** |
|
790 |
* Get the value of a logging property. |
|
791 |
* The method returns null if the property is not found. |
|
792 |
* @param name property name |
|
793 |
* @return property value |
|
794 |
*/ |
|
795 |
public String getProperty(String name) { |
|
796 |
return props.getProperty(name); |
|
797 |
} |
|
798 |
||
799 |
// Package private method to get a String property. |
|
800 |
// If the property is not defined we return the given |
|
801 |
// default value. |
|
802 |
String getStringProperty(String name, String defaultValue) { |
|
803 |
String val = getProperty(name); |
|
804 |
if (val == null) { |
|
805 |
return defaultValue; |
|
806 |
} |
|
807 |
return val.trim(); |
|
808 |
} |
|
809 |
||
810 |
// Package private method to get an integer property. |
|
811 |
// If the property is not defined or cannot be parsed |
|
812 |
// we return the given default value. |
|
813 |
int getIntProperty(String name, int defaultValue) { |
|
814 |
String val = getProperty(name); |
|
815 |
if (val == null) { |
|
816 |
return defaultValue; |
|
817 |
} |
|
818 |
try { |
|
819 |
return Integer.parseInt(val.trim()); |
|
820 |
} catch (Exception ex) { |
|
821 |
return defaultValue; |
|
822 |
} |
|
823 |
} |
|
824 |
||
825 |
// Package private method to get a boolean property. |
|
826 |
// If the property is not defined or cannot be parsed |
|
827 |
// we return the given default value. |
|
828 |
boolean getBooleanProperty(String name, boolean defaultValue) { |
|
829 |
String val = getProperty(name); |
|
830 |
if (val == null) { |
|
831 |
return defaultValue; |
|
832 |
} |
|
833 |
val = val.toLowerCase(); |
|
834 |
if (val.equals("true") || val.equals("1")) { |
|
835 |
return true; |
|
836 |
} else if (val.equals("false") || val.equals("0")) { |
|
837 |
return false; |
|
838 |
} |
|
839 |
return defaultValue; |
|
840 |
} |
|
841 |
||
842 |
// Package private method to get a Level property. |
|
843 |
// If the property is not defined or cannot be parsed |
|
844 |
// we return the given default value. |
|
845 |
Level getLevelProperty(String name, Level defaultValue) { |
|
846 |
String val = getProperty(name); |
|
847 |
if (val == null) { |
|
848 |
return defaultValue; |
|
849 |
} |
|
850 |
try { |
|
851 |
return Level.parse(val.trim()); |
|
852 |
} catch (Exception ex) { |
|
853 |
return defaultValue; |
|
854 |
} |
|
855 |
} |
|
856 |
||
857 |
// Package private method to get a filter property. |
|
858 |
// We return an instance of the class named by the "name" |
|
859 |
// property. If the property is not defined or has problems |
|
860 |
// we return the defaultValue. |
|
861 |
Filter getFilterProperty(String name, Filter defaultValue) { |
|
862 |
String val = getProperty(name); |
|
863 |
try { |
|
864 |
if (val != null) { |
|
865 |
Class clz = ClassLoader.getSystemClassLoader().loadClass(val); |
|
866 |
return (Filter) clz.newInstance(); |
|
867 |
} |
|
868 |
} catch (Exception ex) { |
|
869 |
// We got one of a variety of exceptions in creating the |
|
870 |
// class or creating an instance. |
|
871 |
// Drop through. |
|
872 |
} |
|
873 |
// We got an exception. Return the defaultValue. |
|
874 |
return defaultValue; |
|
875 |
} |
|
876 |
||
877 |
||
878 |
// Package private method to get a formatter property. |
|
879 |
// We return an instance of the class named by the "name" |
|
880 |
// property. If the property is not defined or has problems |
|
881 |
// we return the defaultValue. |
|
882 |
Formatter getFormatterProperty(String name, Formatter defaultValue) { |
|
883 |
String val = getProperty(name); |
|
884 |
try { |
|
885 |
if (val != null) { |
|
886 |
Class clz = ClassLoader.getSystemClassLoader().loadClass(val); |
|
887 |
return (Formatter) clz.newInstance(); |
|
888 |
} |
|
889 |
} catch (Exception ex) { |
|
890 |
// We got one of a variety of exceptions in creating the |
|
891 |
// class or creating an instance. |
|
892 |
// Drop through. |
|
893 |
} |
|
894 |
// We got an exception. Return the defaultValue. |
|
895 |
return defaultValue; |
|
896 |
} |
|
897 |
||
898 |
// Private method to load the global handlers. |
|
899 |
// We do the real work lazily, when the global handlers |
|
900 |
// are first used. |
|
901 |
private synchronized void initializeGlobalHandlers() { |
|
902 |
if (initializedGlobalHandlers) { |
|
903 |
return; |
|
904 |
} |
|
905 |
||
906 |
initializedGlobalHandlers = true; |
|
907 |
||
908 |
if (deathImminent) { |
|
909 |
// Aaargh... |
|
910 |
// The VM is shutting down and our exit hook has been called. |
|
911 |
// Avoid allocating global handlers. |
|
912 |
return; |
|
913 |
} |
|
914 |
loadLoggerHandlers(rootLogger, null, "handlers"); |
|
915 |
} |
|
916 |
||
917 |
||
918 |
private Permission ourPermission = new LoggingPermission("control", null); |
|
919 |
||
920 |
/** |
|
921 |
* Check that the current context is trusted to modify the logging |
|
922 |
* configuration. This requires LoggingPermission("control"). |
|
923 |
* <p> |
|
924 |
* If the check fails we throw a SecurityException, otherwise |
|
925 |
* we return normally. |
|
926 |
* |
|
927 |
* @exception SecurityException if a security manager exists and if |
|
928 |
* the caller does not have LoggingPermission("control"). |
|
929 |
*/ |
|
930 |
public void checkAccess() throws SecurityException { |
|
931 |
SecurityManager sm = System.getSecurityManager(); |
|
932 |
if (sm == null) { |
|
933 |
return; |
|
934 |
} |
|
935 |
sm.checkPermission(ourPermission); |
|
936 |
} |
|
937 |
||
938 |
// Nested class to represent a node in our tree of named loggers. |
|
939 |
private static class LogNode { |
|
940 |
HashMap<String,LogNode> children; |
|
941 |
WeakReference<Logger> loggerRef; |
|
942 |
LogNode parent; |
|
943 |
||
944 |
LogNode(LogNode parent) { |
|
945 |
this.parent = parent; |
|
946 |
} |
|
947 |
||
948 |
// Recursive method to walk the tree below a node and set |
|
949 |
// a new parent logger. |
|
950 |
void walkAndSetParent(Logger parent) { |
|
951 |
if (children == null) { |
|
952 |
return; |
|
953 |
} |
|
954 |
Iterator<LogNode> values = children.values().iterator(); |
|
955 |
while (values.hasNext()) { |
|
956 |
LogNode node = values.next(); |
|
957 |
WeakReference<Logger> ref = node.loggerRef; |
|
958 |
Logger logger = (ref == null) ? null : ref.get(); |
|
959 |
if (logger == null) { |
|
960 |
node.walkAndSetParent(parent); |
|
961 |
} else { |
|
962 |
doSetParent(logger, parent); |
|
963 |
} |
|
964 |
} |
|
965 |
} |
|
966 |
} |
|
967 |
||
968 |
// We use a subclass of Logger for the root logger, so |
|
969 |
// that we only instantiate the global handlers when they |
|
970 |
// are first needed. |
|
971 |
private class RootLogger extends Logger { |
|
972 |
||
973 |
private RootLogger() { |
|
974 |
super("", null); |
|
975 |
setLevel(defaultLevel); |
|
976 |
} |
|
977 |
||
978 |
public void log(LogRecord record) { |
|
979 |
// Make sure that the global handlers have been instantiated. |
|
980 |
initializeGlobalHandlers(); |
|
981 |
super.log(record); |
|
982 |
} |
|
983 |
||
984 |
public void addHandler(Handler h) { |
|
985 |
initializeGlobalHandlers(); |
|
986 |
super.addHandler(h); |
|
987 |
} |
|
988 |
||
989 |
public void removeHandler(Handler h) { |
|
990 |
initializeGlobalHandlers(); |
|
991 |
super.removeHandler(h); |
|
992 |
} |
|
993 |
||
994 |
public Handler[] getHandlers() { |
|
995 |
initializeGlobalHandlers(); |
|
996 |
return super.getHandlers(); |
|
997 |
} |
|
998 |
} |
|
999 |
||
1000 |
||
1001 |
// Private method to be called when the configuration has |
|
1002 |
// changed to apply any level settings to any pre-existing loggers. |
|
1003 |
synchronized private void setLevelsOnExistingLoggers() { |
|
1004 |
Enumeration enum_ = props.propertyNames(); |
|
1005 |
while (enum_.hasMoreElements()) { |
|
1006 |
String key = (String)enum_.nextElement(); |
|
1007 |
if (!key.endsWith(".level")) { |
|
1008 |
// Not a level definition. |
|
1009 |
continue; |
|
1010 |
} |
|
1011 |
int ix = key.length() - 6; |
|
1012 |
String name = key.substring(0, ix); |
|
1013 |
Level level = getLevelProperty(key, null); |
|
1014 |
if (level == null) { |
|
1015 |
System.err.println("Bad level value for property: " + key); |
|
1016 |
continue; |
|
1017 |
} |
|
1018 |
Logger l = getLogger(name); |
|
1019 |
if (l == null) { |
|
1020 |
continue; |
|
1021 |
} |
|
1022 |
l.setLevel(level); |
|
1023 |
} |
|
1024 |
} |
|
1025 |
||
1026 |
// Management Support |
|
1027 |
private static LoggingMXBean loggingMXBean = null; |
|
1028 |
/** |
|
1029 |
* String representation of the |
|
1030 |
* {@link javax.management.ObjectName} for {@link LoggingMXBean}. |
|
1031 |
* @since 1.5 |
|
1032 |
*/ |
|
1033 |
public final static String LOGGING_MXBEAN_NAME |
|
1034 |
= "java.util.logging:type=Logging"; |
|
1035 |
||
1036 |
/** |
|
1037 |
* Returns <tt>LoggingMXBean</tt> for managing loggers. |
|
1038 |
* The <tt>LoggingMXBean</tt> can also obtained from the |
|
1039 |
* {@link java.lang.management.ManagementFactory#getPlatformMBeanServer |
|
1040 |
* platform <tt>MBeanServer</tt>} method. |
|
1041 |
* |
|
1042 |
* @return a {@link LoggingMXBean} object. |
|
1043 |
* |
|
1044 |
* @see java.lang.management.ManagementFactory |
|
1045 |
* @since 1.5 |
|
1046 |
*/ |
|
1047 |
public static synchronized LoggingMXBean getLoggingMXBean() { |
|
1048 |
if (loggingMXBean == null) { |
|
1049 |
loggingMXBean = new Logging(); |
|
1050 |
} |
|
1051 |
return loggingMXBean; |
|
1052 |
} |
|
1053 |
||
1054 |
} |