Logger.java 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194
  1. /* Logger.java -- a class for logging messages
  2. Copyright (C) 2002, 2004, 2006, 2007 Free Software Foundation, Inc.
  3. This file is part of GNU Classpath.
  4. GNU Classpath is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2, or (at your option)
  7. any later version.
  8. GNU Classpath is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GNU Classpath; see the file COPYING. If not, write to the
  14. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  15. 02110-1301 USA.
  16. Linking this library statically or dynamically with other modules is
  17. making a combined work based on this library. Thus, the terms and
  18. conditions of the GNU General Public License cover the whole
  19. combination.
  20. As a special exception, the copyright holders of this library give you
  21. permission to link this library with independent modules to produce an
  22. executable, regardless of the license terms of these independent
  23. modules, and to copy and distribute the resulting executable under
  24. terms of your choice, provided that you also meet, for each linked
  25. independent module, the terms and conditions of the license of that
  26. module. An independent module is a module which is not derived from
  27. or based on this library. If you modify this library, you may extend
  28. this exception to your version of the library, but you are not
  29. obligated to do so. If you do not wish to do so, delete this
  30. exception statement from your version. */
  31. package java.util.logging;
  32. import gnu.java.lang.CPStringBuilder;
  33. import java.util.List;
  34. import java.util.MissingResourceException;
  35. import java.util.ResourceBundle;
  36. import java.security.AccessController;
  37. import java.security.PrivilegedAction;
  38. /**
  39. * A Logger is used for logging information about events. Usually, there is a
  40. * seprate logger for each subsystem or component, although there is a shared
  41. * instance for components that make only occasional use of the logging
  42. * framework.
  43. * <p>
  44. * It is common to name a logger after the name of a corresponding Java package.
  45. * Loggers are organized into a hierarchical namespace; for example, the logger
  46. * <code>"org.gnu.foo"</code> is the <em>parent</em> of logger
  47. * <code>"org.gnu.foo.bar"</code>.
  48. * <p>
  49. * A logger for a named subsystem can be obtained through {@link
  50. * java.util.logging.Logger#getLogger(java.lang.String)}. However, only code
  51. * which has been granted the permission to control the logging infrastructure
  52. * will be allowed to customize that logger. Untrusted code can obtain a
  53. * private, anonymous logger through {@link #getAnonymousLogger()} if it wants
  54. * to perform any modifications to the logger.
  55. * <p>
  56. * FIXME: Write more documentation.
  57. *
  58. * @author Sascha Brawer (brawer@acm.org)
  59. */
  60. public class Logger
  61. {
  62. static final Logger root = new Logger("", null);
  63. /**
  64. * A logger provided to applications that make only occasional use of the
  65. * logging framework, typically early prototypes. Serious products are
  66. * supposed to create and use their own Loggers, so they can be controlled
  67. * individually.
  68. */
  69. public static final Logger global;
  70. /**
  71. * Use to lock methods on this class instead of calling synchronize on methods
  72. * to avoid deadlocks. Yeah, no kidding, we got them :)
  73. */
  74. private static final Object[] lock = new Object[0];
  75. static
  76. {
  77. // Our class might be initialized from an unprivileged context
  78. global = (Logger) AccessController.doPrivileged(new PrivilegedAction()
  79. {
  80. public Object run()
  81. {
  82. return getLogger("global");
  83. }
  84. });
  85. }
  86. /**
  87. * The name of the Logger, or <code>null</code> if the logger is anonymous.
  88. * <p>
  89. * A previous version of the GNU Classpath implementation granted untrusted
  90. * code the permission to control any logger whose name was null. However,
  91. * test code revealed that the Sun J2SE 1.4 reference implementation enforces
  92. * the security control for any logger that was not created through
  93. * getAnonymousLogger, even if it has a null name. Therefore, a separate flag
  94. * {@link Logger#anonymous} was introduced.
  95. */
  96. private final String name;
  97. /**
  98. * The name of the resource bundle used for localization.
  99. * <p>
  100. * This variable cannot be declared as <code>final</code> because its value
  101. * can change as a result of calling getLogger(String,String).
  102. */
  103. private String resourceBundleName;
  104. /**
  105. * The resource bundle used for localization.
  106. * <p>
  107. * This variable cannot be declared as <code>final</code> because its value
  108. * can change as a result of calling getLogger(String,String).
  109. */
  110. private ResourceBundle resourceBundle;
  111. private Filter filter;
  112. private final List handlerList = new java.util.ArrayList(4);
  113. private Handler[] handlers = new Handler[0];
  114. /**
  115. * Indicates whether or not this logger is anonymous. While a
  116. * LoggingPermission is required for any modifications to a normal logger,
  117. * untrusted code can obtain an anonymous logger and modify it according to
  118. * its needs.
  119. * <p>
  120. * A previous version of the GNU Classpath implementation granted access to
  121. * every logger whose name was null. However, test code revealed that the Sun
  122. * J2SE 1.4 reference implementation enforces the security control for any
  123. * logger that was not created through getAnonymousLogger, even if it has a
  124. * null name.
  125. */
  126. private boolean anonymous;
  127. private boolean useParentHandlers;
  128. private Level level;
  129. private Logger parent;
  130. /**
  131. * Constructs a Logger for a subsystem. Most applications do not need to
  132. * create new Loggers explicitly; instead, they should call the static factory
  133. * methods {@link #getLogger(java.lang.String,java.lang.String) getLogger}
  134. * (with ResourceBundle for localization) or
  135. * {@link #getLogger(java.lang.String) getLogger} (without ResourceBundle),
  136. * respectively.
  137. *
  138. * @param name the name for the logger, for example "java.awt" or
  139. * "com.foo.bar". The name should be based on the name of the
  140. * package issuing log records and consist of dot-separated Java
  141. * identifiers.
  142. * @param resourceBundleName the name of a resource bundle for localizing
  143. * messages, or <code>null</code> to indicate that messages do
  144. * not need to be localized.
  145. * @throws java.util.MissingResourceException if
  146. * <code>resourceBundleName</code> is not <code>null</code>
  147. * and no such bundle could be located.
  148. */
  149. protected Logger(String name, String resourceBundleName)
  150. throws MissingResourceException
  151. {
  152. this.name = name;
  153. this.resourceBundleName = resourceBundleName;
  154. if (resourceBundleName == null)
  155. resourceBundle = null;
  156. else
  157. resourceBundle = ResourceBundle.getBundle(resourceBundleName);
  158. level = null;
  159. /*
  160. * This is null when the root logger is being constructed, and the root
  161. * logger afterwards.
  162. */
  163. parent = root;
  164. useParentHandlers = (parent != null);
  165. }
  166. /**
  167. * Finds a registered logger for a subsystem, or creates one in case no logger
  168. * has been registered yet.
  169. *
  170. * @param name the name for the logger, for example "java.awt" or
  171. * "com.foo.bar". The name should be based on the name of the
  172. * package issuing log records and consist of dot-separated Java
  173. * identifiers.
  174. * @throws IllegalArgumentException if a logger for the subsystem identified
  175. * by <code>name</code> has already been created, but uses a a
  176. * resource bundle for localizing messages.
  177. * @throws NullPointerException if <code>name</code> is <code>null</code>.
  178. * @return a logger for the subsystem specified by <code>name</code> that
  179. * does not localize messages.
  180. */
  181. public static Logger getLogger(String name)
  182. {
  183. return getLogger(name, null);
  184. }
  185. /**
  186. * Finds a registered logger for a subsystem, or creates one in case no logger
  187. * has been registered yet.
  188. * <p>
  189. * If a logger with the specified name has already been registered, the
  190. * behavior depends on the resource bundle that is currently associated with
  191. * the existing logger.
  192. * <ul>
  193. * <li>If the existing logger uses the same resource bundle as specified by
  194. * <code>resourceBundleName</code>, the existing logger is returned.</li>
  195. * <li>If the existing logger currently does not localize messages, the
  196. * existing logger is modified to use the bundle specified by
  197. * <code>resourceBundleName</code>. The existing logger is then returned.
  198. * Therefore, all subsystems currently using this logger will produce
  199. * localized messages from now on.</li>
  200. * <li>If the existing logger already has an associated resource bundle, but
  201. * a different one than specified by <code>resourceBundleName</code>, an
  202. * <code>IllegalArgumentException</code> is thrown.</li>
  203. * </ul>
  204. *
  205. * @param name the name for the logger, for example "java.awt" or
  206. * "org.gnu.foo". The name should be based on the name of the
  207. * package issuing log records and consist of dot-separated Java
  208. * identifiers.
  209. * @param resourceBundleName the name of a resource bundle for localizing
  210. * messages, or <code>null</code> to indicate that messages do
  211. * not need to be localized.
  212. * @return a logger for the subsystem specified by <code>name</code>.
  213. * @throws java.util.MissingResourceException if
  214. * <code>resourceBundleName</code> is not <code>null</code>
  215. * and no such bundle could be located.
  216. * @throws IllegalArgumentException if a logger for the subsystem identified
  217. * by <code>name</code> has already been created, but uses a
  218. * different resource bundle for localizing messages.
  219. * @throws NullPointerException if <code>name</code> is <code>null</code>.
  220. */
  221. public static Logger getLogger(String name, String resourceBundleName)
  222. {
  223. LogManager lm = LogManager.getLogManager();
  224. Logger result;
  225. if (name == null)
  226. throw new NullPointerException();
  227. /*
  228. * Without synchronized(lm), it could happen that another thread would
  229. * create a logger between our calls to getLogger and addLogger. While
  230. * addLogger would indicate this by returning false, we could not be sure
  231. * that this other logger was still existing when we called getLogger a
  232. * second time in order to retrieve it -- note that LogManager is only
  233. * allowed to keep weak references to registered loggers, so Loggers can be
  234. * garbage collected at any time in general, and between our call to
  235. * addLogger and our second call go getLogger in particular. Of course, we
  236. * assume here that LogManager.addLogger etc. are synchronizing on the
  237. * global LogManager object. There is a comment in the implementation of
  238. * LogManager.addLogger referring to this comment here, so that any change
  239. * in the synchronization of LogManager will be reflected here.
  240. */
  241. synchronized (lock)
  242. {
  243. synchronized (lm)
  244. {
  245. result = lm.getLogger(name);
  246. if (result == null)
  247. {
  248. boolean couldBeAdded;
  249. result = new Logger(name, resourceBundleName);
  250. couldBeAdded = lm.addLogger(result);
  251. if (! couldBeAdded)
  252. throw new IllegalStateException("cannot register new logger");
  253. }
  254. else
  255. {
  256. /*
  257. * The logger already exists. Make sure it uses the same
  258. * resource bundle for localizing messages.
  259. */
  260. String existingBundleName = result.getResourceBundleName();
  261. /*
  262. * The Sun J2SE 1.4 reference implementation will return the
  263. * registered logger object, even if it does not have a resource
  264. * bundle associated with it. However, it seems to change the
  265. * resourceBundle of the registered logger to the bundle whose
  266. * name was passed to getLogger.
  267. */
  268. if ((existingBundleName == null) &&
  269. (resourceBundleName != null))
  270. {
  271. /*
  272. * If ResourceBundle.getBundle throws an exception, the
  273. * existing logger will be unchanged. This would be
  274. * different if the assignment to resourceBundleName came
  275. * first.
  276. */
  277. result.resourceBundle =
  278. ResourceBundle.getBundle(resourceBundleName);
  279. result.resourceBundleName = resourceBundleName;
  280. return result;
  281. }
  282. if ((existingBundleName != resourceBundleName)
  283. && ((existingBundleName == null)
  284. || !existingBundleName.equals(resourceBundleName)))
  285. {
  286. throw new IllegalArgumentException();
  287. }
  288. }
  289. }
  290. }
  291. return result;
  292. }
  293. /**
  294. * Creates a new, unnamed logger. Unnamed loggers are not registered in the
  295. * namespace of the LogManager, and no special security permission is required
  296. * for changing their state. Therefore, untrusted applets are able to modify
  297. * their private logger instance obtained through this method.
  298. * <p>
  299. * The parent of the newly created logger will the the root logger, from which
  300. * the level threshold and the handlers are inherited.
  301. */
  302. public static Logger getAnonymousLogger()
  303. {
  304. return getAnonymousLogger(null);
  305. }
  306. /**
  307. * Creates a new, unnamed logger. Unnamed loggers are not registered in the
  308. * namespace of the LogManager, and no special security permission is required
  309. * for changing their state. Therefore, untrusted applets are able to modify
  310. * their private logger instance obtained through this method.
  311. * <p>
  312. * The parent of the newly created logger will the the root logger, from which
  313. * the level threshold and the handlers are inherited.
  314. *
  315. * @param resourceBundleName the name of a resource bundle for localizing
  316. * messages, or <code>null</code> to indicate that messages do
  317. * not need to be localized.
  318. * @throws java.util.MissingResourceException if
  319. * <code>resourceBundleName</code> is not <code>null</code>
  320. * and no such bundle could be located.
  321. */
  322. public static Logger getAnonymousLogger(String resourceBundleName)
  323. throws MissingResourceException
  324. {
  325. Logger result;
  326. result = new Logger(null, resourceBundleName);
  327. result.anonymous = true;
  328. return result;
  329. }
  330. /**
  331. * Returns the name of the resource bundle that is being used for localizing
  332. * messages.
  333. *
  334. * @return the name of the resource bundle used for localizing messages, or
  335. * <code>null</code> if the parent's resource bundle is used for
  336. * this purpose.
  337. */
  338. public String getResourceBundleName()
  339. {
  340. synchronized (lock)
  341. {
  342. return resourceBundleName;
  343. }
  344. }
  345. /**
  346. * Returns the resource bundle that is being used for localizing messages.
  347. *
  348. * @return the resource bundle used for localizing messages, or
  349. * <code>null</code> if the parent's resource bundle is used for
  350. * this purpose.
  351. */
  352. public ResourceBundle getResourceBundle()
  353. {
  354. synchronized (lock)
  355. {
  356. return resourceBundle;
  357. }
  358. }
  359. /**
  360. * Returns the severity level threshold for this <code>Handler</code>. All
  361. * log records with a lower severity level will be discarded; a log record of
  362. * the same or a higher level will be published unless an installed
  363. * <code>Filter</code> decides to discard it.
  364. *
  365. * @return the severity level below which all log messages will be discarded,
  366. * or <code>null</code> if the logger inherits the threshold from
  367. * its parent.
  368. */
  369. public Level getLevel()
  370. {
  371. synchronized (lock)
  372. {
  373. return level;
  374. }
  375. }
  376. /**
  377. * Returns whether or not a message of the specified level would be logged by
  378. * this logger.
  379. *
  380. * @throws NullPointerException if <code>level</code> is <code>null</code>.
  381. */
  382. public boolean isLoggable(Level level)
  383. {
  384. synchronized (lock)
  385. {
  386. if (this.level != null)
  387. return this.level.intValue() <= level.intValue();
  388. if (parent != null)
  389. return parent.isLoggable(level);
  390. else
  391. return false;
  392. }
  393. }
  394. /**
  395. * Sets the severity level threshold for this <code>Handler</code>. All log
  396. * records with a lower severity level will be discarded immediately. A log
  397. * record of the same or a higher level will be published unless an installed
  398. * <code>Filter</code> decides to discard it.
  399. *
  400. * @param level the severity level below which all log messages will be
  401. * discarded, or <code>null</code> to indicate that the logger
  402. * should inherit the threshold from its parent.
  403. * @throws SecurityException if this logger is not anonymous, a security
  404. * manager exists, and the caller is not granted the permission to
  405. * control the logging infrastructure by having
  406. * LoggingPermission("control"). Untrusted code can obtain an
  407. * anonymous logger through the static factory method
  408. * {@link #getAnonymousLogger(java.lang.String) getAnonymousLogger}.
  409. */
  410. public void setLevel(Level level)
  411. {
  412. synchronized (lock)
  413. {
  414. /*
  415. * An application is allowed to control an anonymous logger without
  416. * having the permission to control the logging infrastructure.
  417. */
  418. if (! anonymous)
  419. LogManager.getLogManager().checkAccess();
  420. this.level = level;
  421. }
  422. }
  423. public Filter getFilter()
  424. {
  425. synchronized (lock)
  426. {
  427. return filter;
  428. }
  429. }
  430. /**
  431. * @throws SecurityException if this logger is not anonymous, a security
  432. * manager exists, and the caller is not granted the permission to
  433. * control the logging infrastructure by having
  434. * LoggingPermission("control"). Untrusted code can obtain an
  435. * anonymous logger through the static factory method
  436. * {@link #getAnonymousLogger(java.lang.String) getAnonymousLogger}.
  437. */
  438. public void setFilter(Filter filter) throws SecurityException
  439. {
  440. synchronized (lock)
  441. {
  442. /*
  443. * An application is allowed to control an anonymous logger without
  444. * having the permission to control the logging infrastructure.
  445. */
  446. if (! anonymous)
  447. LogManager.getLogManager().checkAccess();
  448. this.filter = filter;
  449. }
  450. }
  451. /**
  452. * Returns the name of this logger.
  453. *
  454. * @return the name of this logger, or <code>null</code> if the logger is
  455. * anonymous.
  456. */
  457. public String getName()
  458. {
  459. /*
  460. * Note that the name of a logger cannot be changed during its lifetime, so
  461. * no synchronization is needed.
  462. */
  463. return name;
  464. }
  465. /**
  466. * Passes a record to registered handlers, provided the record is considered
  467. * as loggable both by {@link #isLoggable(Level)} and a possibly installed
  468. * custom {@link #setFilter(Filter) filter}.
  469. * <p>
  470. * If the logger has been configured to use parent handlers, the record will
  471. * be forwarded to the parent of this logger in addition to being processed by
  472. * the handlers registered with this logger.
  473. * <p>
  474. * The other logging methods in this class are convenience methods that merely
  475. * create a new LogRecord and pass it to this method. Therefore, subclasses
  476. * usually just need to override this single method for customizing the
  477. * logging behavior.
  478. *
  479. * @param record the log record to be inspected and possibly forwarded.
  480. */
  481. public void log(LogRecord record)
  482. {
  483. synchronized (lock)
  484. {
  485. if (!isLoggable(record.getLevel()))
  486. return;
  487. if ((filter != null) && ! filter.isLoggable(record))
  488. return;
  489. /*
  490. * If no logger name has been set for the log record, use the name of
  491. * this logger.
  492. */
  493. if (record.getLoggerName() == null)
  494. record.setLoggerName(name);
  495. /*
  496. * Avoid that some other thread is changing the logger hierarchy while
  497. * we are traversing it.
  498. */
  499. synchronized (LogManager.getLogManager())
  500. {
  501. Logger curLogger = this;
  502. do
  503. {
  504. /*
  505. * The Sun J2SE 1.4 reference implementation seems to call the
  506. * filter only for the logger whose log method is called, never
  507. * for any of its parents. Also, parent loggers publish log
  508. * record whatever their level might be. This is pretty weird,
  509. * but GNU Classpath tries to be as compatible as possible to
  510. * the reference implementation.
  511. */
  512. for (int i = 0; i < curLogger.handlers.length; i++)
  513. curLogger.handlers[i].publish(record);
  514. if (curLogger.getUseParentHandlers() == false)
  515. break;
  516. curLogger = curLogger.getParent();
  517. }
  518. while (parent != null);
  519. }
  520. }
  521. }
  522. public void log(Level level, String message)
  523. {
  524. if (isLoggable(level))
  525. log(level, message, (Object[]) null);
  526. }
  527. public void log(Level level, String message, Object param)
  528. {
  529. synchronized (lock)
  530. {
  531. if (isLoggable(level))
  532. {
  533. StackTraceElement caller = getCallerStackFrame();
  534. logp(level, caller != null ? caller.getClassName() : "<unknown>",
  535. caller != null ? caller.getMethodName() : "<unknown>",
  536. message, param);
  537. }
  538. }
  539. }
  540. public void log(Level level, String message, Object[] params)
  541. {
  542. synchronized (lock)
  543. {
  544. if (isLoggable(level))
  545. {
  546. StackTraceElement caller = getCallerStackFrame();
  547. logp(level, caller != null ? caller.getClassName() : "<unknown>",
  548. caller != null ? caller.getMethodName() : "<unknown>",
  549. message, params);
  550. }
  551. }
  552. }
  553. public void log(Level level, String message, Throwable thrown)
  554. {
  555. synchronized (lock)
  556. {
  557. if (isLoggable(level))
  558. {
  559. StackTraceElement caller = getCallerStackFrame();
  560. logp(level, caller != null ? caller.getClassName() : "<unknown>",
  561. caller != null ? caller.getMethodName() : "<unknown>",
  562. message, thrown);
  563. }
  564. }
  565. }
  566. public void logp(Level level, String sourceClass, String sourceMethod,
  567. String message)
  568. {
  569. synchronized (lock)
  570. {
  571. logp(level, sourceClass, sourceMethod, message, (Object[]) null);
  572. }
  573. }
  574. public void logp(Level level, String sourceClass, String sourceMethod,
  575. String message, Object param)
  576. {
  577. synchronized (lock)
  578. {
  579. logp(level, sourceClass, sourceMethod, message, new Object[] { param });
  580. }
  581. }
  582. private ResourceBundle findResourceBundle()
  583. {
  584. synchronized (lock)
  585. {
  586. if (resourceBundle != null)
  587. return resourceBundle;
  588. if (parent != null)
  589. return parent.findResourceBundle();
  590. return null;
  591. }
  592. }
  593. private void logImpl(Level level, String sourceClass, String sourceMethod,
  594. String message, Object[] params)
  595. {
  596. synchronized (lock)
  597. {
  598. LogRecord rec = new LogRecord(level, message);
  599. rec.setResourceBundle(findResourceBundle());
  600. rec.setSourceClassName(sourceClass);
  601. rec.setSourceMethodName(sourceMethod);
  602. rec.setParameters(params);
  603. log(rec);
  604. }
  605. }
  606. public void logp(Level level, String sourceClass, String sourceMethod,
  607. String message, Object[] params)
  608. {
  609. synchronized (lock)
  610. {
  611. logImpl(level, sourceClass, sourceMethod, message, params);
  612. }
  613. }
  614. public void logp(Level level, String sourceClass, String sourceMethod,
  615. String message, Throwable thrown)
  616. {
  617. synchronized (lock)
  618. {
  619. LogRecord rec = new LogRecord(level, message);
  620. rec.setResourceBundle(resourceBundle);
  621. rec.setSourceClassName(sourceClass);
  622. rec.setSourceMethodName(sourceMethod);
  623. rec.setThrown(thrown);
  624. log(rec);
  625. }
  626. }
  627. public void logrb(Level level, String sourceClass, String sourceMethod,
  628. String bundleName, String message)
  629. {
  630. synchronized (lock)
  631. {
  632. logrb(level, sourceClass, sourceMethod, bundleName, message,
  633. (Object[]) null);
  634. }
  635. }
  636. public void logrb(Level level, String sourceClass, String sourceMethod,
  637. String bundleName, String message, Object param)
  638. {
  639. synchronized (lock)
  640. {
  641. logrb(level, sourceClass, sourceMethod, bundleName, message,
  642. new Object[] { param });
  643. }
  644. }
  645. public void logrb(Level level, String sourceClass, String sourceMethod,
  646. String bundleName, String message, Object[] params)
  647. {
  648. synchronized (lock)
  649. {
  650. LogRecord rec = new LogRecord(level, message);
  651. rec.setResourceBundleName(bundleName);
  652. rec.setSourceClassName(sourceClass);
  653. rec.setSourceMethodName(sourceMethod);
  654. rec.setParameters(params);
  655. log(rec);
  656. }
  657. }
  658. public void logrb(Level level, String sourceClass, String sourceMethod,
  659. String bundleName, String message, Throwable thrown)
  660. {
  661. synchronized (lock)
  662. {
  663. LogRecord rec = new LogRecord(level, message);
  664. rec.setResourceBundleName(bundleName);
  665. rec.setSourceClassName(sourceClass);
  666. rec.setSourceMethodName(sourceMethod);
  667. rec.setThrown(thrown);
  668. log(rec);
  669. }
  670. }
  671. public void entering(String sourceClass, String sourceMethod)
  672. {
  673. synchronized (lock)
  674. {
  675. if (isLoggable(Level.FINER))
  676. logp(Level.FINER, sourceClass, sourceMethod, "ENTRY");
  677. }
  678. }
  679. public void entering(String sourceClass, String sourceMethod, Object param)
  680. {
  681. synchronized (lock)
  682. {
  683. if (isLoggable(Level.FINER))
  684. logp(Level.FINER, sourceClass, sourceMethod, "ENTRY {0}", param);
  685. }
  686. }
  687. public void entering(String sourceClass, String sourceMethod, Object[] params)
  688. {
  689. synchronized (lock)
  690. {
  691. if (isLoggable(Level.FINER))
  692. {
  693. CPStringBuilder buf = new CPStringBuilder(80);
  694. buf.append("ENTRY");
  695. for (int i = 0; i < params.length; i++)
  696. {
  697. buf.append(" {");
  698. buf.append(i);
  699. buf.append('}');
  700. }
  701. logp(Level.FINER, sourceClass, sourceMethod, buf.toString(), params);
  702. }
  703. }
  704. }
  705. public void exiting(String sourceClass, String sourceMethod)
  706. {
  707. synchronized (lock)
  708. {
  709. if (isLoggable(Level.FINER))
  710. logp(Level.FINER, sourceClass, sourceMethod, "RETURN");
  711. }
  712. }
  713. public void exiting(String sourceClass, String sourceMethod, Object result)
  714. {
  715. synchronized (lock)
  716. {
  717. if (isLoggable(Level.FINER))
  718. logp(Level.FINER, sourceClass, sourceMethod, "RETURN {0}", result);
  719. }
  720. }
  721. public void throwing(String sourceClass, String sourceMethod, Throwable thrown)
  722. {
  723. synchronized (lock)
  724. {
  725. if (isLoggable(Level.FINER))
  726. logp(Level.FINER, sourceClass, sourceMethod, "THROW", thrown);
  727. }
  728. }
  729. /**
  730. * Logs a message with severity level SEVERE, indicating a serious failure
  731. * that prevents normal program execution. Messages at this level should be
  732. * understandable to an inexperienced, non-technical end user. Ideally, they
  733. * explain in simple words what actions the user can take in order to resolve
  734. * the problem.
  735. *
  736. * @see Level#SEVERE
  737. * @param message the message text, also used as look-up key if the logger is
  738. * localizing messages with a resource bundle. While it is possible
  739. * to pass <code>null</code>, this is not recommended, since a
  740. * logging message without text is unlikely to be helpful.
  741. */
  742. public void severe(String message)
  743. {
  744. synchronized (lock)
  745. {
  746. if (isLoggable(Level.SEVERE))
  747. log(Level.SEVERE, message);
  748. }
  749. }
  750. /**
  751. * Logs a message with severity level WARNING, indicating a potential problem
  752. * that does not prevent normal program execution. Messages at this level
  753. * should be understandable to an inexperienced, non-technical end user.
  754. * Ideally, they explain in simple words what actions the user can take in
  755. * order to resolve the problem.
  756. *
  757. * @see Level#WARNING
  758. * @param message the message text, also used as look-up key if the logger is
  759. * localizing messages with a resource bundle. While it is possible
  760. * to pass <code>null</code>, this is not recommended, since a
  761. * logging message without text is unlikely to be helpful.
  762. */
  763. public void warning(String message)
  764. {
  765. synchronized (lock)
  766. {
  767. if (isLoggable(Level.WARNING))
  768. log(Level.WARNING, message);
  769. }
  770. }
  771. /**
  772. * Logs a message with severity level INFO. {@link Level#INFO} is intended for
  773. * purely informational messages that do not indicate error or warning
  774. * situations. In the default logging configuration, INFO messages will be
  775. * written to the system console. For this reason, the INFO level should be
  776. * used only for messages that are important to end users and system
  777. * administrators. Messages at this level should be understandable to an
  778. * inexperienced, non-technical user.
  779. *
  780. * @param message the message text, also used as look-up key if the logger is
  781. * localizing messages with a resource bundle. While it is possible
  782. * to pass <code>null</code>, this is not recommended, since a
  783. * logging message without text is unlikely to be helpful.
  784. */
  785. public void info(String message)
  786. {
  787. synchronized (lock)
  788. {
  789. if (isLoggable(Level.INFO))
  790. log(Level.INFO, message);
  791. }
  792. }
  793. /**
  794. * Logs a message with severity level CONFIG. {@link Level#CONFIG} is intended
  795. * for static configuration messages, for example about the windowing
  796. * environment, the operating system version, etc.
  797. *
  798. * @param message the message text, also used as look-up key if the logger is
  799. * localizing messages with a resource bundle. While it is possible
  800. * to pass <code>null</code>, this is not recommended, since a
  801. * logging message without text is unlikely to be helpful.
  802. */
  803. public void config(String message)
  804. {
  805. synchronized (lock)
  806. {
  807. if (isLoggable(Level.CONFIG))
  808. log(Level.CONFIG, message);
  809. }
  810. }
  811. /**
  812. * Logs a message with severity level FINE. {@link Level#FINE} is intended for
  813. * messages that are relevant for developers using the component generating
  814. * log messages. Examples include minor, recoverable failures, or possible
  815. * inefficiencies.
  816. *
  817. * @param message the message text, also used as look-up key if the logger is
  818. * localizing messages with a resource bundle. While it is possible
  819. * to pass <code>null</code>, this is not recommended, since a
  820. * logging message without text is unlikely to be helpful.
  821. */
  822. public void fine(String message)
  823. {
  824. synchronized (lock)
  825. {
  826. if (isLoggable(Level.FINE))
  827. log(Level.FINE, message);
  828. }
  829. }
  830. /**
  831. * Logs a message with severity level FINER. {@link Level#FINER} is intended
  832. * for rather detailed tracing, for example entering a method, returning from
  833. * a method, or throwing an exception.
  834. *
  835. * @param message the message text, also used as look-up key if the logger is
  836. * localizing messages with a resource bundle. While it is possible
  837. * to pass <code>null</code>, this is not recommended, since a
  838. * logging message without text is unlikely to be helpful.
  839. */
  840. public void finer(String message)
  841. {
  842. synchronized (lock)
  843. {
  844. if (isLoggable(Level.FINER))
  845. log(Level.FINER, message);
  846. }
  847. }
  848. /**
  849. * Logs a message with severity level FINEST. {@link Level#FINEST} is intended
  850. * for highly detailed tracing, for example reaching a certain point inside
  851. * the body of a method.
  852. *
  853. * @param message the message text, also used as look-up key if the logger is
  854. * localizing messages with a resource bundle. While it is possible
  855. * to pass <code>null</code>, this is not recommended, since a
  856. * logging message without text is unlikely to be helpful.
  857. */
  858. public void finest(String message)
  859. {
  860. synchronized (lock)
  861. {
  862. if (isLoggable(Level.FINEST))
  863. log(Level.FINEST, message);
  864. }
  865. }
  866. /**
  867. * Adds a handler to the set of handlers that get notified when a log record
  868. * is to be published.
  869. *
  870. * @param handler the handler to be added.
  871. * @throws NullPointerException if <code>handler</code> is <code>null</code>.
  872. * @throws SecurityException if this logger is not anonymous, a security
  873. * manager exists, and the caller is not granted the permission to
  874. * control the logging infrastructure by having
  875. * LoggingPermission("control"). Untrusted code can obtain an
  876. * anonymous logger through the static factory method
  877. * {@link #getAnonymousLogger(java.lang.String) getAnonymousLogger}.
  878. */
  879. public void addHandler(Handler handler) throws SecurityException
  880. {
  881. synchronized (lock)
  882. {
  883. if (handler == null)
  884. throw new NullPointerException();
  885. /*
  886. * An application is allowed to control an anonymous logger without
  887. * having the permission to control the logging infrastructure.
  888. */
  889. if (! anonymous)
  890. LogManager.getLogManager().checkAccess();
  891. if (! handlerList.contains(handler))
  892. {
  893. handlerList.add(handler);
  894. handlers = getHandlers();
  895. }
  896. }
  897. }
  898. /**
  899. * Removes a handler from the set of handlers that get notified when a log
  900. * record is to be published.
  901. *
  902. * @param handler the handler to be removed.
  903. * @throws SecurityException if this logger is not anonymous, a security
  904. * manager exists, and the caller is not granted the permission to
  905. * control the logging infrastructure by having
  906. * LoggingPermission("control"). Untrusted code can obtain an
  907. * anonymous logger through the static factory method {@link
  908. * #getAnonymousLogger(java.lang.String) getAnonymousLogger}.
  909. * @throws NullPointerException if <code>handler</code> is <code>null</code>.
  910. */
  911. public void removeHandler(Handler handler) throws SecurityException
  912. {
  913. synchronized (lock)
  914. {
  915. /*
  916. * An application is allowed to control an anonymous logger without
  917. * having the permission to control the logging infrastructure.
  918. */
  919. if (! anonymous)
  920. LogManager.getLogManager().checkAccess();
  921. if (handler == null)
  922. throw new NullPointerException();
  923. handlerList.remove(handler);
  924. handlers = getHandlers();
  925. }
  926. }
  927. /**
  928. * Returns the handlers currently registered for this Logger. When a log
  929. * record has been deemed as being loggable, it will be passed to all
  930. * registered handlers for publication. In addition, if the logger uses parent
  931. * handlers (see {@link #getUseParentHandlers() getUseParentHandlers} and
  932. * {@link #setUseParentHandlers(boolean) setUseParentHandlers}, the log
  933. * record will be passed to the parent's handlers.
  934. */
  935. public Handler[] getHandlers()
  936. {
  937. synchronized (lock)
  938. {
  939. /*
  940. * We cannot return our internal handlers array because we do not have
  941. * any guarantee that the caller would not change the array entries.
  942. */
  943. return (Handler[]) handlerList.toArray(new Handler[handlerList.size()]);
  944. }
  945. }
  946. /**
  947. * Returns whether or not this Logger forwards log records to handlers
  948. * registered for its parent loggers.
  949. *
  950. * @return <code>false</code> if this Logger sends log records merely to
  951. * Handlers registered with itself; <code>true</code> if this Logger
  952. * sends log records not only to Handlers registered with itself, but
  953. * also to those Handlers registered with parent loggers.
  954. */
  955. public boolean getUseParentHandlers()
  956. {
  957. synchronized (lock)
  958. {
  959. return useParentHandlers;
  960. }
  961. }
  962. /**
  963. * Sets whether or not this Logger forwards log records to handlers registered
  964. * for its parent loggers.
  965. *
  966. * @param useParentHandlers <code>false</code> to let this Logger send log
  967. * records merely to Handlers registered with itself;
  968. * <code>true</code> to let this Logger send log records not only
  969. * to Handlers registered with itself, but also to those Handlers
  970. * registered with parent loggers.
  971. * @throws SecurityException if this logger is not anonymous, a security
  972. * manager exists, and the caller is not granted the permission to
  973. * control the logging infrastructure by having
  974. * LoggingPermission("control"). Untrusted code can obtain an
  975. * anonymous logger through the static factory method
  976. * {@link #getAnonymousLogger(java.lang.String) getAnonymousLogger}.
  977. */
  978. public void setUseParentHandlers(boolean useParentHandlers)
  979. {
  980. synchronized (lock)
  981. {
  982. /*
  983. * An application is allowed to control an anonymous logger without
  984. * having the permission to control the logging infrastructure.
  985. */
  986. if (! anonymous)
  987. LogManager.getLogManager().checkAccess();
  988. this.useParentHandlers = useParentHandlers;
  989. }
  990. }
  991. /**
  992. * Returns the parent of this logger. By default, the parent is assigned by
  993. * the LogManager by inspecting the logger's name.
  994. *
  995. * @return the parent of this logger (as detemined by the LogManager by
  996. * inspecting logger names), the root logger if no other logger has a
  997. * name which is a prefix of this logger's name, or <code>null</code>
  998. * for the root logger.
  999. */
  1000. public Logger getParent()
  1001. {
  1002. synchronized (lock)
  1003. {
  1004. return parent;
  1005. }
  1006. }
  1007. /**
  1008. * Sets the parent of this logger. Usually, applications do not call this
  1009. * method directly. Instead, the LogManager will ensure that the tree of
  1010. * loggers reflects the hierarchical logger namespace. Basically, this method
  1011. * should not be public at all, but the GNU implementation follows the API
  1012. * specification.
  1013. *
  1014. * @throws NullPointerException if <code>parent</code> is <code>null</code>.
  1015. * @throws SecurityException if this logger is not anonymous, a security
  1016. * manager exists, and the caller is not granted the permission to
  1017. * control the logging infrastructure by having
  1018. * LoggingPermission("control"). Untrusted code can obtain an
  1019. * anonymous logger through the static factory method
  1020. * {@link #getAnonymousLogger(java.lang.String) getAnonymousLogger}.
  1021. */
  1022. public void setParent(Logger parent)
  1023. {
  1024. synchronized (lock)
  1025. {
  1026. if (parent == null)
  1027. throw new NullPointerException();
  1028. if (this == root)
  1029. throw new IllegalArgumentException(
  1030. "the root logger can only have a null parent");
  1031. /*
  1032. * An application is allowed to control an anonymous logger without
  1033. * having the permission to control the logging infrastructure.
  1034. */
  1035. if (! anonymous)
  1036. LogManager.getLogManager().checkAccess();
  1037. this.parent = parent;
  1038. }
  1039. }
  1040. /**
  1041. * Gets the StackTraceElement of the first class that is not this class. That
  1042. * should be the initial caller of a logging method.
  1043. *
  1044. * @return caller of the initial logging method or null if unknown.
  1045. */
  1046. private StackTraceElement getCallerStackFrame()
  1047. {
  1048. Throwable t = new Throwable();
  1049. StackTraceElement[] stackTrace = t.getStackTrace();
  1050. int index = 0;
  1051. // skip to stackentries until this class
  1052. while (index < stackTrace.length
  1053. && ! stackTrace[index].getClassName().equals(getClass().getName()))
  1054. index++;
  1055. // skip the stackentries of this class
  1056. while (index < stackTrace.length
  1057. && stackTrace[index].getClassName().equals(getClass().getName()))
  1058. index++;
  1059. return index < stackTrace.length ? stackTrace[index] : null;
  1060. }
  1061. /**
  1062. * Reset and close handlers attached to this logger. This function is package
  1063. * private because it must only be available to the LogManager.
  1064. */
  1065. void resetLogger()
  1066. {
  1067. for (int i = 0; i < handlers.length; i++)
  1068. {
  1069. handlers[i].close();
  1070. handlerList.remove(handlers[i]);
  1071. }
  1072. handlers = getHandlers();
  1073. }
  1074. }