Logger.java 41.1 KB
Newer Older
Tom Tromey committed
1
/* Logger.java -- a class for logging messages
2
   Copyright (C) 2002, 2004, 2006, 2007 Free Software Foundation, Inc.
Tom Tromey committed
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40

This file is part of GNU Classpath.

GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.

GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */


package java.util.logging;

41 42
import gnu.java.lang.CPStringBuilder;

Tom Tromey committed
43 44 45
import java.util.List;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
46 47
import java.security.AccessController;
import java.security.PrivilegedAction;
Tom Tromey committed
48 49

/**
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
 * A Logger is used for logging information about events. Usually, there is a
 * seprate logger for each subsystem or component, although there is a shared
 * instance for components that make only occasional use of the logging
 * framework.
 * <p>
 * It is common to name a logger after the name of a corresponding Java package.
 * Loggers are organized into a hierarchical namespace; for example, the logger
 * <code>"org.gnu.foo"</code> is the <em>parent</em> of logger
 * <code>"org.gnu.foo.bar"</code>.
 * <p>
 * A logger for a named subsystem can be obtained through {@link
 * java.util.logging.Logger#getLogger(java.lang.String)}. However, only code
 * which has been granted the permission to control the logging infrastructure
 * will be allowed to customize that logger. Untrusted code can obtain a
 * private, anonymous logger through {@link #getAnonymousLogger()} if it wants
 * to perform any modifications to the logger.
 * <p>
 * FIXME: Write more documentation.
68
 *
Tom Tromey committed
69 70 71 72
 * @author Sascha Brawer (brawer@acm.org)
 */
public class Logger
{
73 74
  static final Logger root = new Logger("", null);

Tom Tromey committed
75
  /**
76 77 78 79
   * A logger provided to applications that make only occasional use of the
   * logging framework, typically early prototypes. Serious products are
   * supposed to create and use their own Loggers, so they can be controlled
   * individually.
Tom Tromey committed
80
   */
81 82
  public static final Logger global;

83 84 85 86 87
  /**
   * Use to lock methods on this class instead of calling synchronize on methods
   * to avoid deadlocks. Yeah, no kidding, we got them :)
   */
  private static final Object[] lock = new Object[0];
88

89 90 91
  static
    {
      // Our class might be initialized from an unprivileged context
92 93 94 95 96 97 98
      global = (Logger) AccessController.doPrivileged(new PrivilegedAction()
      {
        public Object run()
        {
          return getLogger("global");
        }
      });
99
    }
Tom Tromey committed
100 101

  /**
102 103 104 105 106 107 108 109
   * The name of the Logger, or <code>null</code> if the logger is anonymous.
   * <p>
   * A previous version of the GNU Classpath implementation granted untrusted
   * code the permission to control any logger whose name was null. However,
   * test code revealed that the Sun J2SE 1.4 reference implementation enforces
   * the security control for any logger that was not created through
   * getAnonymousLogger, even if it has a null name. Therefore, a separate flag
   * {@link Logger#anonymous} was introduced.
Tom Tromey committed
110 111 112 113 114
   */
  private final String name;

  /**
   * The name of the resource bundle used for localization.
115 116 117
   * <p>
   * This variable cannot be declared as <code>final</code> because its value
   * can change as a result of calling getLogger(String,String).
Tom Tromey committed
118 119 120 121 122
   */
  private String resourceBundleName;

  /**
   * The resource bundle used for localization.
123 124 125
   * <p>
   * This variable cannot be declared as <code>final</code> because its value
   * can change as a result of calling getLogger(String,String).
Tom Tromey committed
126 127 128 129 130 131
   */
  private ResourceBundle resourceBundle;

  private Filter filter;

  private final List handlerList = new java.util.ArrayList(4);
132

Tom Tromey committed
133 134 135
  private Handler[] handlers = new Handler[0];

  /**
136 137 138 139 140 141 142 143 144 145
   * Indicates whether or not this logger is anonymous. While a
   * LoggingPermission is required for any modifications to a normal logger,
   * untrusted code can obtain an anonymous logger and modify it according to
   * its needs.
   * <p>
   * A previous version of the GNU Classpath implementation granted access to
   * every logger whose name was null. However, test code revealed that the Sun
   * J2SE 1.4 reference implementation enforces the security control for any
   * logger that was not created through getAnonymousLogger, even if it has a
   * null name.
Tom Tromey committed
146 147 148 149 150 151 152 153 154 155
   */
  private boolean anonymous;

  private boolean useParentHandlers;

  private Level level;

  private Logger parent;

  /**
156 157 158
   * Constructs a Logger for a subsystem. Most applications do not need to
   * create new Loggers explicitly; instead, they should call the static factory
   * methods {@link #getLogger(java.lang.String,java.lang.String) getLogger}
Tom Tromey committed
159
   * (with ResourceBundle for localization) or
160 161
   * {@link #getLogger(java.lang.String) getLogger} (without ResourceBundle),
   * respectively.
162
   *
163 164 165 166 167 168 169
   * @param name the name for the logger, for example "java.awt" or
   *            "com.foo.bar". The name should be based on the name of the
   *            package issuing log records and consist of dot-separated Java
   *            identifiers.
   * @param resourceBundleName the name of a resource bundle for localizing
   *            messages, or <code>null</code> to indicate that messages do
   *            not need to be localized.
Tom Tromey committed
170
   * @throws java.util.MissingResourceException if
171 172
   *             <code>resourceBundleName</code> is not <code>null</code>
   *             and no such bundle could be located.
Tom Tromey committed
173 174
   */
  protected Logger(String name, String resourceBundleName)
175
      throws MissingResourceException
Tom Tromey committed
176 177 178 179 180 181 182 183 184 185 186
  {
    this.name = name;
    this.resourceBundleName = resourceBundleName;

    if (resourceBundleName == null)
      resourceBundle = null;
    else
      resourceBundle = ResourceBundle.getBundle(resourceBundleName);

    level = null;

187 188 189
    /*
     * This is null when the root logger is being constructed, and the root
     * logger afterwards.
Tom Tromey committed
190
     */
191
    parent = root;
Tom Tromey committed
192 193 194 195 196

    useParentHandlers = (parent != null);
  }

  /**
197 198
   * Finds a registered logger for a subsystem, or creates one in case no logger
   * has been registered yet.
199
   *
200 201 202 203 204 205 206 207 208 209
   * @param name the name for the logger, for example "java.awt" or
   *            "com.foo.bar". The name should be based on the name of the
   *            package issuing log records and consist of dot-separated Java
   *            identifiers.
   * @throws IllegalArgumentException if a logger for the subsystem identified
   *             by <code>name</code> has already been created, but uses a a
   *             resource bundle for localizing messages.
   * @throws NullPointerException if <code>name</code> is <code>null</code>.
   * @return a logger for the subsystem specified by <code>name</code> that
   *         does not localize messages.
Tom Tromey committed
210 211 212 213 214 215 216
   */
  public static Logger getLogger(String name)
  {
    return getLogger(name, null);
  }

  /**
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
   * Finds a registered logger for a subsystem, or creates one in case no logger
   * has been registered yet.
   * <p>
   * If a logger with the specified name has already been registered, the
   * behavior depends on the resource bundle that is currently associated with
   * the existing logger.
   * <ul>
   * <li>If the existing logger uses the same resource bundle as specified by
   * <code>resourceBundleName</code>, the existing logger is returned.</li>
   * <li>If the existing logger currently does not localize messages, the
   * existing logger is modified to use the bundle specified by
   * <code>resourceBundleName</code>. The existing logger is then returned.
   * Therefore, all subsystems currently using this logger will produce
   * localized messages from now on.</li>
   * <li>If the existing logger already has an associated resource bundle, but
   * a different one than specified by <code>resourceBundleName</code>, an
   * <code>IllegalArgumentException</code> is thrown.</li>
   * </ul>
235
   *
236 237 238 239 240 241 242
   * @param name the name for the logger, for example "java.awt" or
   *            "org.gnu.foo". The name should be based on the name of the
   *            package issuing log records and consist of dot-separated Java
   *            identifiers.
   * @param resourceBundleName the name of a resource bundle for localizing
   *            messages, or <code>null</code> to indicate that messages do
   *            not need to be localized.
Tom Tromey committed
243 244
   * @return a logger for the subsystem specified by <code>name</code>.
   * @throws java.util.MissingResourceException if
245 246 247 248 249 250
   *             <code>resourceBundleName</code> is not <code>null</code>
   *             and no such bundle could be located.
   * @throws IllegalArgumentException if a logger for the subsystem identified
   *             by <code>name</code> has already been created, but uses a
   *             different resource bundle for localizing messages.
   * @throws NullPointerException if <code>name</code> is <code>null</code>.
Tom Tromey committed
251 252 253 254
   */
  public static Logger getLogger(String name, String resourceBundleName)
  {
    LogManager lm = LogManager.getLogManager();
255
    Logger result;
Tom Tromey committed
256

257 258
    if (name == null)
      throw new NullPointerException();
Tom Tromey committed
259

260 261 262 263 264 265 266 267 268 269 270 271 272
    /*
     * Without synchronized(lm), it could happen that another thread would
     * create a logger between our calls to getLogger and addLogger. While
     * addLogger would indicate this by returning false, we could not be sure
     * that this other logger was still existing when we called getLogger a
     * second time in order to retrieve it -- note that LogManager is only
     * allowed to keep weak references to registered loggers, so Loggers can be
     * garbage collected at any time in general, and between our call to
     * addLogger and our second call go getLogger in particular. Of course, we
     * assume here that LogManager.addLogger etc. are synchronizing on the
     * global LogManager object. There is a comment in the implementation of
     * LogManager.addLogger referring to this comment here, so that any change
     * in the synchronization of LogManager will be reflected here.
Tom Tromey committed
273
     */
274
    synchronized (lock)
Tom Tromey committed
275
      {
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
        synchronized (lm)
          {
            result = lm.getLogger(name);
            if (result == null)
              {
                boolean couldBeAdded;

                result = new Logger(name, resourceBundleName);
                couldBeAdded = lm.addLogger(result);
                if (! couldBeAdded)
                  throw new IllegalStateException("cannot register new logger");
              }
            else
              {
                /*
                 * The logger already exists. Make sure it uses the same
                 * resource bundle for localizing messages.
                 */
                String existingBundleName = result.getResourceBundleName();

                /*
                 * The Sun J2SE 1.4 reference implementation will return the
                 * registered logger object, even if it does not have a resource
                 * bundle associated with it. However, it seems to change the
                 * resourceBundle of the registered logger to the bundle whose
                 * name was passed to getLogger.
                 */
                if ((existingBundleName == null) &&
                    (resourceBundleName != null))
                  {
                    /*
                     * If ResourceBundle.getBundle throws an exception, the
                     * existing logger will be unchanged. This would be
                     * different if the assignment to resourceBundleName came
                     * first.
                     */
                    result.resourceBundle =
                      ResourceBundle.getBundle(resourceBundleName);

                    result.resourceBundleName = resourceBundleName;
                    return result;
                  }

                if ((existingBundleName != resourceBundleName)
                    && ((existingBundleName == null)
                        || !existingBundleName.equals(resourceBundleName)))
                  {
                    throw new IllegalArgumentException();
                  }
              }
          }
Tom Tromey committed
327 328 329 330 331 332
      }

    return result;
  }

  /**
333 334 335 336 337 338 339
   * Creates a new, unnamed logger. Unnamed loggers are not registered in the
   * namespace of the LogManager, and no special security permission is required
   * for changing their state. Therefore, untrusted applets are able to modify
   * their private logger instance obtained through this method.
   * <p>
   * The parent of the newly created logger will the the root logger, from which
   * the level threshold and the handlers are inherited.
Tom Tromey committed
340 341 342 343 344 345 346
   */
  public static Logger getAnonymousLogger()
  {
    return getAnonymousLogger(null);
  }

  /**
347 348 349 350 351 352 353
   * Creates a new, unnamed logger. Unnamed loggers are not registered in the
   * namespace of the LogManager, and no special security permission is required
   * for changing their state. Therefore, untrusted applets are able to modify
   * their private logger instance obtained through this method.
   * <p>
   * The parent of the newly created logger will the the root logger, from which
   * the level threshold and the handlers are inherited.
354
   *
355 356 357
   * @param resourceBundleName the name of a resource bundle for localizing
   *            messages, or <code>null</code> to indicate that messages do
   *            not need to be localized.
Tom Tromey committed
358
   * @throws java.util.MissingResourceException if
359 360
   *             <code>resourceBundleName</code> is not <code>null</code>
   *             and no such bundle could be located.
Tom Tromey committed
361 362
   */
  public static Logger getAnonymousLogger(String resourceBundleName)
363
      throws MissingResourceException
Tom Tromey committed
364
  {
365
    Logger result;
Tom Tromey committed
366 367 368 369 370 371 372

    result = new Logger(null, resourceBundleName);
    result.anonymous = true;
    return result;
  }

  /**
373 374
   * Returns the name of the resource bundle that is being used for localizing
   * messages.
375
   *
376 377 378
   * @return the name of the resource bundle used for localizing messages, or
   *         <code>null</code> if the parent's resource bundle is used for
   *         this purpose.
Tom Tromey committed
379
   */
380
  public String getResourceBundleName()
Tom Tromey committed
381
  {
382 383 384 385
    synchronized (lock)
      {
        return resourceBundleName;
      }
Tom Tromey committed
386 387 388
  }

  /**
389
   * Returns the resource bundle that is being used for localizing messages.
390
   *
391 392 393
   * @return the resource bundle used for localizing messages, or
   *         <code>null</code> if the parent's resource bundle is used for
   *         this purpose.
Tom Tromey committed
394
   */
395
  public ResourceBundle getResourceBundle()
Tom Tromey committed
396
  {
397 398 399 400
    synchronized (lock)
      {
        return resourceBundle;
      }
Tom Tromey committed
401 402 403
  }

  /**
404 405 406 407
   * Returns the severity level threshold for this <code>Handler</code>. All
   * log records with a lower severity level will be discarded; a log record of
   * the same or a higher level will be published unless an installed
   * <code>Filter</code> decides to discard it.
408
   *
409 410 411
   * @return the severity level below which all log messages will be discarded,
   *         or <code>null</code> if the logger inherits the threshold from
   *         its parent.
Tom Tromey committed
412
   */
413
  public Level getLevel()
Tom Tromey committed
414
  {
415 416 417 418
    synchronized (lock)
      {
        return level;
      }
Tom Tromey committed
419 420 421
  }

  /**
422 423
   * Returns whether or not a message of the specified level would be logged by
   * this logger.
424
   *
425
   * @throws NullPointerException if <code>level</code> is <code>null</code>.
Tom Tromey committed
426
   */
427
  public boolean isLoggable(Level level)
Tom Tromey committed
428
  {
429 430 431 432
    synchronized (lock)
      {
        if (this.level != null)
          return this.level.intValue() <= level.intValue();
Tom Tromey committed
433

434 435 436 437 438
        if (parent != null)
          return parent.isLoggable(level);
        else
          return false;
      }
Tom Tromey committed
439 440 441
  }

  /**
442 443 444 445
   * Sets the severity level threshold for this <code>Handler</code>. All log
   * records with a lower severity level will be discarded immediately. A log
   * record of the same or a higher level will be published unless an installed
   * <code>Filter</code> decides to discard it.
446
   *
447 448 449 450 451 452 453 454 455
   * @param level the severity level below which all log messages will be
   *            discarded, or <code>null</code> to indicate that the logger
   *            should inherit the threshold from its parent.
   * @throws SecurityException if this logger is not anonymous, a security
   *             manager exists, and the caller is not granted the permission to
   *             control the logging infrastructure by having
   *             LoggingPermission("control"). Untrusted code can obtain an
   *             anonymous logger through the static factory method
   *             {@link #getAnonymousLogger(java.lang.String) getAnonymousLogger}.
Tom Tromey committed
456
   */
457
  public void setLevel(Level level)
Tom Tromey committed
458
  {
459 460 461 462 463 464 465 466 467 468 469
    synchronized (lock)
      {
        /*
         * An application is allowed to control an anonymous logger without
         * having the permission to control the logging infrastructure.
         */
        if (! anonymous)
          LogManager.getLogManager().checkAccess();

        this.level = level;
      }
Tom Tromey committed
470 471
  }

472
  public Filter getFilter()
Tom Tromey committed
473
  {
474 475 476 477
    synchronized (lock)
      {
        return filter;
      }
Tom Tromey committed
478 479 480
  }

  /**
481 482 483 484 485 486
   * @throws SecurityException if this logger is not anonymous, a security
   *             manager exists, and the caller is not granted the permission to
   *             control the logging infrastructure by having
   *             LoggingPermission("control"). Untrusted code can obtain an
   *             anonymous logger through the static factory method
   *             {@link #getAnonymousLogger(java.lang.String) getAnonymousLogger}.
Tom Tromey committed
487
   */
488
  public void setFilter(Filter filter) throws SecurityException
Tom Tromey committed
489
  {
490 491 492 493 494 495 496 497 498 499 500
    synchronized (lock)
      {
        /*
         * An application is allowed to control an anonymous logger without
         * having the permission to control the logging infrastructure.
         */
        if (! anonymous)
          LogManager.getLogManager().checkAccess();

        this.filter = filter;
      }
Tom Tromey committed
501 502 503 504
  }

  /**
   * Returns the name of this logger.
505
   *
506 507
   * @return the name of this logger, or <code>null</code> if the logger is
   *         anonymous.
Tom Tromey committed
508 509 510
   */
  public String getName()
  {
511 512 513
    /*
     * Note that the name of a logger cannot be changed during its lifetime, so
     * no synchronization is needed.
Tom Tromey committed
514 515 516 517 518
     */
    return name;
  }

  /**
519 520 521 522 523 524 525 526 527 528 529 530
   * Passes a record to registered handlers, provided the record is considered
   * as loggable both by {@link #isLoggable(Level)} and a possibly installed
   * custom {@link #setFilter(Filter) filter}.
   * <p>
   * If the logger has been configured to use parent handlers, the record will
   * be forwarded to the parent of this logger in addition to being processed by
   * the handlers registered with this logger.
   * <p>
   * The other logging methods in this class are convenience methods that merely
   * create a new LogRecord and pass it to this method. Therefore, subclasses
   * usually just need to override this single method for customizing the
   * logging behavior.
531
   *
Tom Tromey committed
532 533
   * @param record the log record to be inspected and possibly forwarded.
   */
534
  public void log(LogRecord record)
Tom Tromey committed
535
  {
536
    synchronized (lock)
Tom Tromey committed
537
      {
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
        if (!isLoggable(record.getLevel()))
          return;

        if ((filter != null) && ! filter.isLoggable(record))
          return;

        /*
         * If no logger name has been set for the log record, use the name of
         * this logger.
         */
        if (record.getLoggerName() == null)
          record.setLoggerName(name);

        /*
         * Avoid that some other thread is changing the logger hierarchy while
         * we are traversing it.
         */
        synchronized (LogManager.getLogManager())
          {
            Logger curLogger = this;

            do
              {
                /*
                 * The Sun J2SE 1.4 reference implementation seems to call the
                 * filter only for the logger whose log method is called, never
                 * for any of its parents. Also, parent loggers publish log
                 * record whatever their level might be. This is pretty weird,
                 * but GNU Classpath tries to be as compatible as possible to
                 * the reference implementation.
                 */
                for (int i = 0; i < curLogger.handlers.length; i++)
                  curLogger.handlers[i].publish(record);

                if (curLogger.getUseParentHandlers() == false)
                  break;

                curLogger = curLogger.getParent();
              }
            while (parent != null);
          }
Tom Tromey committed
579 580 581 582 583
      }
  }

  public void log(Level level, String message)
  {
Tom Tromey committed
584 585
    if (isLoggable(level))
      log(level, message, (Object[]) null);
Tom Tromey committed
586 587
  }

588
  public void log(Level level, String message, Object param)
Tom Tromey committed
589
  {
590
    synchronized (lock)
Tom Tromey committed
591
      {
592 593 594 595 596 597 598
        if (isLoggable(level))
          {
            StackTraceElement caller = getCallerStackFrame();
            logp(level, caller != null ? caller.getClassName() : "<unknown>",
                 caller != null ? caller.getMethodName() : "<unknown>",
                 message, param);
          }
Tom Tromey committed
599
      }
Tom Tromey committed
600 601
  }

602
  public void log(Level level, String message, Object[] params)
Tom Tromey committed
603
  {
604
    synchronized (lock)
Tom Tromey committed
605
      {
606 607 608 609 610 611 612 613
        if (isLoggable(level))
          {
            StackTraceElement caller = getCallerStackFrame();
            logp(level, caller != null ? caller.getClassName() : "<unknown>",
                 caller != null ? caller.getMethodName() : "<unknown>",
                 message, params);

          }
Tom Tromey committed
614
      }
Tom Tromey committed
615 616
  }

617
  public void log(Level level, String message, Throwable thrown)
Tom Tromey committed
618
  {
619
    synchronized (lock)
Tom Tromey committed
620
      {
621 622 623 624 625 626 627
        if (isLoggable(level))
          {
            StackTraceElement caller = getCallerStackFrame();
            logp(level, caller != null ? caller.getClassName() : "<unknown>",
                 caller != null ? caller.getMethodName() : "<unknown>",
                 message, thrown);
          }
Tom Tromey committed
628
      }
Tom Tromey committed
629 630
  }

631 632
  public void logp(Level level, String sourceClass, String sourceMethod,
                   String message)
Tom Tromey committed
633
  {
634 635 636 637
    synchronized (lock)
      {
        logp(level, sourceClass, sourceMethod, message, (Object[]) null);
      }
Tom Tromey committed
638 639
  }

640 641
  public void logp(Level level, String sourceClass, String sourceMethod,
                   String message, Object param)
Tom Tromey committed
642
  {
643 644 645 646
    synchronized (lock)
      {
        logp(level, sourceClass, sourceMethod, message, new Object[] { param });
      }
Tom Tromey committed
647

648
  }
Tom Tromey committed
649

650
  private ResourceBundle findResourceBundle()
Tom Tromey committed
651
  {
652 653 654 655
    synchronized (lock)
      {
        if (resourceBundle != null)
          return resourceBundle;
Tom Tromey committed
656

657 658
        if (parent != null)
          return parent.findResourceBundle();
Tom Tromey committed
659

660 661
        return null;
      }
Tom Tromey committed
662 663
  }

664 665
  private void logImpl(Level level, String sourceClass, String sourceMethod,
                       String message, Object[] params)
Tom Tromey committed
666
  {
667 668 669
    synchronized (lock)
      {
        LogRecord rec = new LogRecord(level, message);
Tom Tromey committed
670

671 672 673 674
        rec.setResourceBundle(findResourceBundle());
        rec.setSourceClassName(sourceClass);
        rec.setSourceMethodName(sourceMethod);
        rec.setParameters(params);
Tom Tromey committed
675

676 677
        log(rec);
      }
Tom Tromey committed
678 679
  }

680 681
  public void logp(Level level, String sourceClass, String sourceMethod,
                   String message, Object[] params)
Tom Tromey committed
682
  {
683 684 685 686
    synchronized (lock)
      {
        logImpl(level, sourceClass, sourceMethod, message, params);
      }
Tom Tromey committed
687 688
  }

689 690
  public void logp(Level level, String sourceClass, String sourceMethod,
                   String message, Throwable thrown)
Tom Tromey committed
691
  {
692 693 694
    synchronized (lock)
      {
        LogRecord rec = new LogRecord(level, message);
Tom Tromey committed
695

696 697 698 699
        rec.setResourceBundle(resourceBundle);
        rec.setSourceClassName(sourceClass);
        rec.setSourceMethodName(sourceMethod);
        rec.setThrown(thrown);
Tom Tromey committed
700

701 702
        log(rec);
      }
Tom Tromey committed
703 704
  }

705 706
  public void logrb(Level level, String sourceClass, String sourceMethod,
                    String bundleName, String message)
Tom Tromey committed
707
  {
708 709 710 711 712
    synchronized (lock)
      {
        logrb(level, sourceClass, sourceMethod, bundleName, message,
              (Object[]) null);
      }
Tom Tromey committed
713 714
  }

715 716
  public void logrb(Level level, String sourceClass, String sourceMethod,
                    String bundleName, String message, Object param)
Tom Tromey committed
717
  {
718 719 720 721 722
    synchronized (lock)
      {
        logrb(level, sourceClass, sourceMethod, bundleName, message,
              new Object[] { param });
      }
Tom Tromey committed
723 724
  }

725 726
  public void logrb(Level level, String sourceClass, String sourceMethod,
                    String bundleName, String message, Object[] params)
Tom Tromey committed
727
  {
728 729 730
    synchronized (lock)
      {
        LogRecord rec = new LogRecord(level, message);
Tom Tromey committed
731

732 733 734 735
        rec.setResourceBundleName(bundleName);
        rec.setSourceClassName(sourceClass);
        rec.setSourceMethodName(sourceMethod);
        rec.setParameters(params);
Tom Tromey committed
736

737 738
        log(rec);
      }
Tom Tromey committed
739 740
  }

741 742
  public void logrb(Level level, String sourceClass, String sourceMethod,
                    String bundleName, String message, Throwable thrown)
Tom Tromey committed
743
  {
744 745 746
    synchronized (lock)
      {
        LogRecord rec = new LogRecord(level, message);
Tom Tromey committed
747

748 749 750 751
        rec.setResourceBundleName(bundleName);
        rec.setSourceClassName(sourceClass);
        rec.setSourceMethodName(sourceMethod);
        rec.setThrown(thrown);
Tom Tromey committed
752

753 754
        log(rec);
      }
Tom Tromey committed
755 756
  }

757
  public void entering(String sourceClass, String sourceMethod)
Tom Tromey committed
758
  {
759 760 761 762 763
    synchronized (lock)
      {
        if (isLoggable(Level.FINER))
          logp(Level.FINER, sourceClass, sourceMethod, "ENTRY");
      }
Tom Tromey committed
764 765
  }

766
  public void entering(String sourceClass, String sourceMethod, Object param)
Tom Tromey committed
767
  {
768 769 770 771 772
    synchronized (lock)
      {
        if (isLoggable(Level.FINER))
          logp(Level.FINER, sourceClass, sourceMethod, "ENTRY {0}", param);
      }
Tom Tromey committed
773 774
  }

775
  public void entering(String sourceClass, String sourceMethod, Object[] params)
Tom Tromey committed
776
  {
777
    synchronized (lock)
Tom Tromey committed
778
      {
779 780
        if (isLoggable(Level.FINER))
          {
781
            CPStringBuilder buf = new CPStringBuilder(80);
782 783 784 785 786 787 788 789 790 791
            buf.append("ENTRY");
            for (int i = 0; i < params.length; i++)
              {
                buf.append(" {");
                buf.append(i);
                buf.append('}');
              }

            logp(Level.FINER, sourceClass, sourceMethod, buf.toString(), params);
          }
Tom Tromey committed
792 793 794
      }
  }

795
  public void exiting(String sourceClass, String sourceMethod)
Tom Tromey committed
796
  {
797 798 799 800 801
    synchronized (lock)
      {
        if (isLoggable(Level.FINER))
          logp(Level.FINER, sourceClass, sourceMethod, "RETURN");
      }
Tom Tromey committed
802 803
  }

804
  public void exiting(String sourceClass, String sourceMethod, Object result)
Tom Tromey committed
805
  {
806 807 808 809 810
    synchronized (lock)
      {
        if (isLoggable(Level.FINER))
          logp(Level.FINER, sourceClass, sourceMethod, "RETURN {0}", result);
      }
Tom Tromey committed
811 812
  }

813
  public void throwing(String sourceClass, String sourceMethod, Throwable thrown)
Tom Tromey committed
814
  {
815 816 817 818 819
    synchronized (lock)
      {
        if (isLoggable(Level.FINER))
          logp(Level.FINER, sourceClass, sourceMethod, "THROW", thrown);
      }
Tom Tromey committed
820 821 822
  }

  /**
823 824 825 826 827
   * Logs a message with severity level SEVERE, indicating a serious failure
   * that prevents normal program execution. Messages at this level should be
   * understandable to an inexperienced, non-technical end user. Ideally, they
   * explain in simple words what actions the user can take in order to resolve
   * the problem.
828
   *
Tom Tromey committed
829
   * @see Level#SEVERE
830 831 832 833
   * @param message the message text, also used as look-up key if the logger is
   *            localizing messages with a resource bundle. While it is possible
   *            to pass <code>null</code>, this is not recommended, since a
   *            logging message without text is unlikely to be helpful.
Tom Tromey committed
834
   */
835
  public void severe(String message)
Tom Tromey committed
836
  {
837 838 839 840 841
    synchronized (lock)
      {
        if (isLoggable(Level.SEVERE))
          log(Level.SEVERE, message);
      }
Tom Tromey committed
842 843 844
  }

  /**
845 846 847 848 849
   * Logs a message with severity level WARNING, indicating a potential problem
   * that does not prevent normal program execution. Messages at this level
   * should be understandable to an inexperienced, non-technical end user.
   * Ideally, they explain in simple words what actions the user can take in
   * order to resolve the problem.
850
   *
Tom Tromey committed
851
   * @see Level#WARNING
852 853 854 855
   * @param message the message text, also used as look-up key if the logger is
   *            localizing messages with a resource bundle. While it is possible
   *            to pass <code>null</code>, this is not recommended, since a
   *            logging message without text is unlikely to be helpful.
Tom Tromey committed
856
   */
857
  public void warning(String message)
Tom Tromey committed
858
  {
859 860 861 862 863
    synchronized (lock)
      {
        if (isLoggable(Level.WARNING))
          log(Level.WARNING, message);
      }
Tom Tromey committed
864 865 866
  }

  /**
867 868 869 870 871 872 873
   * Logs a message with severity level INFO. {@link Level#INFO} is intended for
   * purely informational messages that do not indicate error or warning
   * situations. In the default logging configuration, INFO messages will be
   * written to the system console. For this reason, the INFO level should be
   * used only for messages that are important to end users and system
   * administrators. Messages at this level should be understandable to an
   * inexperienced, non-technical user.
874
   *
875 876 877 878
   * @param message the message text, also used as look-up key if the logger is
   *            localizing messages with a resource bundle. While it is possible
   *            to pass <code>null</code>, this is not recommended, since a
   *            logging message without text is unlikely to be helpful.
Tom Tromey committed
879
   */
880
  public void info(String message)
Tom Tromey committed
881
  {
882 883 884 885 886
    synchronized (lock)
      {
        if (isLoggable(Level.INFO))
          log(Level.INFO, message);
      }
Tom Tromey committed
887 888 889
  }

  /**
890 891 892
   * Logs a message with severity level CONFIG. {@link Level#CONFIG} is intended
   * for static configuration messages, for example about the windowing
   * environment, the operating system version, etc.
893
   *
894 895 896 897
   * @param message the message text, also used as look-up key if the logger is
   *            localizing messages with a resource bundle. While it is possible
   *            to pass <code>null</code>, this is not recommended, since a
   *            logging message without text is unlikely to be helpful.
Tom Tromey committed
898
   */
899
  public void config(String message)
Tom Tromey committed
900
  {
901 902 903 904 905
    synchronized (lock)
      {
        if (isLoggable(Level.CONFIG))
          log(Level.CONFIG, message);
      }
Tom Tromey committed
906 907 908
  }

  /**
909 910 911 912
   * Logs a message with severity level FINE. {@link Level#FINE} is intended for
   * messages that are relevant for developers using the component generating
   * log messages. Examples include minor, recoverable failures, or possible
   * inefficiencies.
913
   *
914 915 916 917
   * @param message the message text, also used as look-up key if the logger is
   *            localizing messages with a resource bundle. While it is possible
   *            to pass <code>null</code>, this is not recommended, since a
   *            logging message without text is unlikely to be helpful.
Tom Tromey committed
918
   */
919
  public void fine(String message)
Tom Tromey committed
920
  {
921 922 923 924 925
    synchronized (lock)
      {
        if (isLoggable(Level.FINE))
          log(Level.FINE, message);
      }
Tom Tromey committed
926 927 928
  }

  /**
929 930 931
   * Logs a message with severity level FINER. {@link Level#FINER} is intended
   * for rather detailed tracing, for example entering a method, returning from
   * a method, or throwing an exception.
932
   *
933 934 935 936
   * @param message the message text, also used as look-up key if the logger is
   *            localizing messages with a resource bundle. While it is possible
   *            to pass <code>null</code>, this is not recommended, since a
   *            logging message without text is unlikely to be helpful.
Tom Tromey committed
937
   */
938
  public void finer(String message)
Tom Tromey committed
939
  {
940 941 942 943 944
    synchronized (lock)
      {
        if (isLoggable(Level.FINER))
          log(Level.FINER, message);
      }
Tom Tromey committed
945 946 947
  }

  /**
948 949 950
   * Logs a message with severity level FINEST. {@link Level#FINEST} is intended
   * for highly detailed tracing, for example reaching a certain point inside
   * the body of a method.
951
   *
952 953 954 955
   * @param message the message text, also used as look-up key if the logger is
   *            localizing messages with a resource bundle. While it is possible
   *            to pass <code>null</code>, this is not recommended, since a
   *            logging message without text is unlikely to be helpful.
Tom Tromey committed
956
   */
957
  public void finest(String message)
Tom Tromey committed
958
  {
959 960 961 962 963
    synchronized (lock)
      {
        if (isLoggable(Level.FINEST))
          log(Level.FINEST, message);
      }
Tom Tromey committed
964 965 966
  }

  /**
967 968
   * Adds a handler to the set of handlers that get notified when a log record
   * is to be published.
969
   *
Tom Tromey committed
970
   * @param handler the handler to be added.
971 972 973 974 975 976 977
   * @throws NullPointerException if <code>handler</code> is <code>null</code>.
   * @throws SecurityException if this logger is not anonymous, a security
   *             manager exists, and the caller is not granted the permission to
   *             control the logging infrastructure by having
   *             LoggingPermission("control"). Untrusted code can obtain an
   *             anonymous logger through the static factory method
   *             {@link #getAnonymousLogger(java.lang.String) getAnonymousLogger}.
Tom Tromey committed
978
   */
979
  public void addHandler(Handler handler) throws SecurityException
Tom Tromey committed
980
  {
981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998
    synchronized (lock)
      {
        if (handler == null)
          throw new NullPointerException();

        /*
         * An application is allowed to control an anonymous logger without
         * having the permission to control the logging infrastructure.
         */
        if (! anonymous)
          LogManager.getLogManager().checkAccess();

        if (! handlerList.contains(handler))
          {
            handlerList.add(handler);
            handlers = getHandlers();
          }
      }
Tom Tromey committed
999 1000 1001
  }

  /**
1002 1003
   * Removes a handler from the set of handlers that get notified when a log
   * record is to be published.
1004
   *
Tom Tromey committed
1005
   * @param handler the handler to be removed.
1006 1007 1008 1009 1010 1011 1012
   * @throws SecurityException if this logger is not anonymous, a security
   *             manager exists, and the caller is not granted the permission to
   *             control the logging infrastructure by having
   *             LoggingPermission("control"). Untrusted code can obtain an
   *             anonymous logger through the static factory method {@link
   *             #getAnonymousLogger(java.lang.String) getAnonymousLogger}.
   * @throws NullPointerException if <code>handler</code> is <code>null</code>.
Tom Tromey committed
1013
   */
1014
  public void removeHandler(Handler handler) throws SecurityException
Tom Tromey committed
1015
  {
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
    synchronized (lock)
      {
        /*
         * An application is allowed to control an anonymous logger without
         * having the permission to control the logging infrastructure.
         */
        if (! anonymous)
          LogManager.getLogManager().checkAccess();

        if (handler == null)
          throw new NullPointerException();

        handlerList.remove(handler);
        handlers = getHandlers();
      }
Tom Tromey committed
1031 1032 1033
  }

  /**
1034 1035 1036 1037 1038 1039
   * Returns the handlers currently registered for this Logger. When a log
   * record has been deemed as being loggable, it will be passed to all
   * registered handlers for publication. In addition, if the logger uses parent
   * handlers (see {@link #getUseParentHandlers() getUseParentHandlers} and
   * {@link #setUseParentHandlers(boolean) setUseParentHandlers}, the log
   * record will be passed to the parent's handlers.
Tom Tromey committed
1040
   */
1041
  public Handler[] getHandlers()
Tom Tromey committed
1042
  {
1043 1044 1045 1046 1047 1048 1049 1050
    synchronized (lock)
      {
        /*
         * We cannot return our internal handlers array because we do not have
         * any guarantee that the caller would not change the array entries.
         */
        return (Handler[]) handlerList.toArray(new Handler[handlerList.size()]);
      }
Tom Tromey committed
1051 1052 1053
  }

  /**
1054 1055
   * Returns whether or not this Logger forwards log records to handlers
   * registered for its parent loggers.
1056
   *
1057 1058 1059 1060
   * @return <code>false</code> if this Logger sends log records merely to
   *         Handlers registered with itself; <code>true</code> if this Logger
   *         sends log records not only to Handlers registered with itself, but
   *         also to those Handlers registered with parent loggers.
Tom Tromey committed
1061
   */
1062
  public boolean getUseParentHandlers()
Tom Tromey committed
1063
  {
1064 1065 1066 1067
    synchronized (lock)
      {
        return useParentHandlers;
      }
Tom Tromey committed
1068 1069 1070
  }

  /**
1071 1072
   * Sets whether or not this Logger forwards log records to handlers registered
   * for its parent loggers.
1073
   *
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
   * @param useParentHandlers <code>false</code> to let this Logger send log
   *            records merely to Handlers registered with itself;
   *            <code>true</code> to let this Logger send log records not only
   *            to Handlers registered with itself, but also to those Handlers
   *            registered with parent loggers.
   * @throws SecurityException if this logger is not anonymous, a security
   *             manager exists, and the caller is not granted the permission to
   *             control the logging infrastructure by having
   *             LoggingPermission("control"). Untrusted code can obtain an
   *             anonymous logger through the static factory method
   *             {@link #getAnonymousLogger(java.lang.String) getAnonymousLogger}.
Tom Tromey committed
1085
   */
1086
  public void setUseParentHandlers(boolean useParentHandlers)
Tom Tromey committed
1087
  {
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
    synchronized (lock)
      {
        /*
         * An application is allowed to control an anonymous logger without
         * having the permission to control the logging infrastructure.
         */
        if (! anonymous)
          LogManager.getLogManager().checkAccess();

        this.useParentHandlers = useParentHandlers;
      }
Tom Tromey committed
1099 1100 1101
  }

  /**
1102 1103
   * Returns the parent of this logger. By default, the parent is assigned by
   * the LogManager by inspecting the logger's name.
1104
   *
1105 1106 1107 1108
   * @return the parent of this logger (as detemined by the LogManager by
   *         inspecting logger names), the root logger if no other logger has a
   *         name which is a prefix of this logger's name, or <code>null</code>
   *         for the root logger.
Tom Tromey committed
1109
   */
1110
  public Logger getParent()
Tom Tromey committed
1111
  {
1112 1113 1114 1115
    synchronized (lock)
      {
        return parent;
      }
Tom Tromey committed
1116 1117 1118
  }

  /**
1119 1120 1121 1122 1123
   * Sets the parent of this logger. Usually, applications do not call this
   * method directly. Instead, the LogManager will ensure that the tree of
   * loggers reflects the hierarchical logger namespace. Basically, this method
   * should not be public at all, but the GNU implementation follows the API
   * specification.
1124
   *
1125 1126 1127 1128 1129 1130 1131
   * @throws NullPointerException if <code>parent</code> is <code>null</code>.
   * @throws SecurityException if this logger is not anonymous, a security
   *             manager exists, and the caller is not granted the permission to
   *             control the logging infrastructure by having
   *             LoggingPermission("control"). Untrusted code can obtain an
   *             anonymous logger through the static factory method
   *             {@link #getAnonymousLogger(java.lang.String) getAnonymousLogger}.
Tom Tromey committed
1132
   */
1133
  public void setParent(Logger parent)
Tom Tromey committed
1134
  {
1135 1136 1137 1138
    synchronized (lock)
      {
        if (parent == null)
          throw new NullPointerException();
Tom Tromey committed
1139

1140 1141 1142
        if (this == root)
          throw new IllegalArgumentException(
                                             "the root logger can only have a null parent");
Tom Tromey committed
1143

1144 1145 1146 1147 1148 1149
        /*
         * An application is allowed to control an anonymous logger without
         * having the permission to control the logging infrastructure.
         */
        if (! anonymous)
          LogManager.getLogManager().checkAccess();
Tom Tromey committed
1150

1151 1152
        this.parent = parent;
      }
Tom Tromey committed
1153
  }
1154

Tom Tromey committed
1155
  /**
1156 1157
   * Gets the StackTraceElement of the first class that is not this class. That
   * should be the initial caller of a logging method.
1158
   *
Tom Tromey committed
1159 1160 1161 1162 1163 1164 1165 1166 1167
   * @return caller of the initial logging method or null if unknown.
   */
  private StackTraceElement getCallerStackFrame()
  {
    Throwable t = new Throwable();
    StackTraceElement[] stackTrace = t.getStackTrace();
    int index = 0;

    // skip to stackentries until this class
1168 1169
    while (index < stackTrace.length
           && ! stackTrace[index].getClassName().equals(getClass().getName()))
Tom Tromey committed
1170 1171 1172
      index++;

    // skip the stackentries of this class
1173 1174
    while (index < stackTrace.length
           && stackTrace[index].getClassName().equals(getClass().getName()))
Tom Tromey committed
1175 1176 1177 1178
      index++;

    return index < stackTrace.length ? stackTrace[index] : null;
  }
1179

Tom Tromey committed
1180 1181
  /**
   * Reset and close handlers attached to this logger. This function is package
1182
   * private because it must only be available to the LogManager.
Tom Tromey committed
1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193
   */
  void resetLogger()
  {
    for (int i = 0; i < handlers.length; i++)
      {
        handlers[i].close();
        handlerList.remove(handlers[i]);
      }
    handlers = getHandlers();
  }
}