PlatformLogger.java 21.1 KB
Newer Older
1 2 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 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 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 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 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 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
/*
 * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Sun designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Sun in the LICENSE file that accompanied this code.
 *
 * This code 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
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
 * CA 95054 USA or visit www.sun.com if you need additional information or
 * have any questions.
 */


package sun.util.logging;

import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.io.File;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.text.MessageFormat;
import java.util.logging.Logger;
import java.util.*;
import sun.misc.JavaLangAccess;
import sun.misc.SharedSecrets;

/**
 * Platform logger provides an API for the JRE components to log
 * messages.  This enables the runtime components to eliminate the
 * static dependency of the logging facility and also defers the
 * java.util.logging initialization until it is enabled.
 * In addition, the PlatformLogger API can be used if the logging
 * module does not exist.
 *
 * If the logging facility is not enabled, the platform loggers
 * will output log messages per the default logging configuration
 * (see below). In this implementation, it does not log the
 * the stack frame information issuing the log message.
 *
 * When the logging facility is enabled (at startup or runtime),
 * the java.util.logging.Logger will be created for each platform
 * logger and all log messages will be forwarded to the Logger
 * to handle.
 *
 * Logging facility is "enabled" when one of the following
 * conditions is met:
 * 1) a system property "java.util.logging.config.class" or
 *    "java.util.logging.config.file" is set
 * 2) java.util.logging.LogManager or java.util.logging.Logger
 *    is referenced that will trigger the logging initialization.
 *
 * Default logging configuration:
 *   global logging level = INFO
 *   handlers = java.util.logging.ConsoleHandler
 *   java.util.logging.ConsoleHandler.level = INFO
 *   java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
 *
 * Limitation:
 * <JAVA_HOME>/lib/logging.properties is the system-wide logging
 * configuration defined in the specification and read in the
 * default case to configure any java.util.logging.Logger instances.
 * Platform loggers will not detect if <JAVA_HOME>/lib/logging.properties
 * is modified. In other words, unless the java.util.logging API
 * is used at runtime or the logging system properties is set,
 * the platform loggers will use the default setting described above.
 * The platform loggers are designed for JDK developers use and
 * this limitation can be workaround with setting
 * -Djava.util.logging.config.file system property.
 *
 * @since 1.7
 */
public class PlatformLogger {
    // Same values as java.util.logging.Level for easy mapping
    public static final int OFF     = Integer.MAX_VALUE;
    public static final int SEVERE  = 1000;
    public static final int WARNING = 900;
    public static final int INFO    = 800;
    public static final int CONFIG  = 700;
    public static final int FINE    = 500;
    public static final int FINER   = 400;
    public static final int FINEST  = 300;
    public static final int ALL     = Integer.MIN_VALUE;

    private static final int defaultLevel = INFO;
    private static boolean loggingEnabled;
    static {
        loggingEnabled = AccessController.doPrivileged(
            new PrivilegedAction<Boolean>() {
                public Boolean run() {
                    String cname = System.getProperty("java.util.logging.config.class");
                    String fname = System.getProperty("java.util.logging.config.file");
                    return (cname != null || fname != null);
                }
            });
    }

    // Table of known loggers.  Maps names to PlatformLoggers.
    private static Map<String,WeakReference<PlatformLogger>> loggers =
        new HashMap<String,WeakReference<PlatformLogger>>();

    /**
     * Returns a PlatformLogger of a given name.
     */
    public static synchronized PlatformLogger getLogger(String name) {
        PlatformLogger log = null;
        WeakReference<PlatformLogger> ref = loggers.get(name);
        if (ref != null) {
            log = ref.get();
        }
        if (log == null) {
            log = new PlatformLogger(name);
            loggers.put(name, new WeakReference<PlatformLogger>(log));
        }
        return log;
    }

    /**
     * Initialize java.util.logging.Logger objects for all platform loggers.
     * This method is called from LogManager.readPrimordialConfiguration().
     */
    public static synchronized void redirectPlatformLoggers() {
        if (loggingEnabled || !JavaLogger.supported) return;

        loggingEnabled = true;
        for (Map.Entry<String, WeakReference<PlatformLogger>> entry : loggers.entrySet()) {
            WeakReference<PlatformLogger> ref = entry.getValue();
            PlatformLogger plog = ref.get();
            if (plog != null) {
                plog.newJavaLogger();
            }
        }
    }

    /**
     * Creates a new JavaLogger that the platform logger uses
     */
    private void newJavaLogger() {
        logger = new JavaLogger(logger.name, logger.effectiveLevel);
    }

    // logger may be replaced with a JavaLogger object
    // when the logging facility is enabled
    private volatile LoggerProxy logger;

    private PlatformLogger(String name) {
        if (loggingEnabled) {
            this.logger = new JavaLogger(name);
        } else {
            this.logger = new LoggerProxy(name);
        }
    }

    /**
     * A convenience method to test if the logger is turned off.
     * (i.e. its level is OFF).
     */
    public boolean isEnabled() {
        return logger.isEnabled();
    }

    /**
     * Gets the name for this platform logger.
     */
    public String getName() {
        return logger.name;
    }

    /**
     * Returns true if a message of the given level would actually
     * be logged by this logger.
     */
    public boolean isLoggable(int level) {
        return logger.isLoggable(level);
    }

    /**
     * Gets the current log level.  Returns 0 if the current effective level
     * is not set (equivalent to Logger.getLevel() returns null).
     */
    public int getLevel() {
        return logger.getLevel();
    }

    /**
     * Sets the log level.
     */
    public void setLevel(int newLevel) {
        logger.setLevel(newLevel);
    }

    /**
     * Logs a SEVERE message.
     */
    public void severe(String msg) {
        logger.doLog(SEVERE, msg);
    }

    public void severe(String msg, Throwable t) {
        logger.doLog(SEVERE, msg, t);
    }

    public void severe(String msg, Object... params) {
        logger.doLog(SEVERE, msg, params);
    }

    /**
     * Logs a WARNING message.
     */
    public void warning(String msg) {
        logger.doLog(WARNING, msg);
    }

    public void warning(String msg, Throwable t) {
        logger.doLog(WARNING, msg, t);
    }

    public void warning(String msg, Object... params) {
        logger.doLog(WARNING, msg, params);
    }

    /**
     * Logs an INFO message.
     */
    public void info(String msg) {
        logger.doLog(INFO, msg);
    }

    public void info(String msg, Throwable t) {
        logger.doLog(INFO, msg, t);
    }

    public void info(String msg, Object... params) {
        logger.doLog(INFO, msg, params);
    }

    /**
     * Logs a CONFIG message.
     */
    public void config(String msg) {
        logger.doLog(CONFIG, msg);
    }

    public void config(String msg, Throwable t) {
        logger.doLog(CONFIG, msg, t);
    }

    public void config(String msg, Object... params) {
        logger.doLog(CONFIG, msg, params);
    }

    /**
     * Logs a FINE message.
     */
    public void fine(String msg) {
        logger.doLog(FINE, msg);
    }

    public void fine(String msg, Throwable t) {
        logger.doLog(FINE, msg, t);
    }

    public void fine(String msg, Object... params) {
        logger.doLog(FINE, msg, params);
    }

    /**
     * Logs a FINER message.
     */
    public void finer(String msg) {
        logger.doLog(FINER, msg);
    }

    public void finer(String msg, Throwable t) {
        logger.doLog(FINER, msg, t);
    }

    public void finer(String msg, Object... params) {
        logger.doLog(FINER, msg, params);
    }

    /**
     * Logs a FINEST message.
     */
    public void finest(String msg) {
        logger.doLog(FINEST, msg);
    }

    public void finest(String msg, Throwable t) {
        logger.doLog(FINEST, msg, t);
    }

    public void finest(String msg, Object... params) {
        logger.doLog(FINEST, msg, params);
    }

    /**
     * Default platform logging support - output messages to
     * System.err - equivalent to ConsoleHandler with SimpleFormatter.
     */
    static class LoggerProxy {
        private static final PrintStream defaultStream = System.err;
        private static final String lineSeparator = AccessController.doPrivileged(
            new PrivilegedAction<String>() {
                public String run() {
                    return System.getProperty("line.separator");
                }
            });

        final String name;
        volatile int levelValue;
        volatile int effectiveLevel = 0; // current effective level value

        LoggerProxy(String name) {
            this(name, defaultLevel);
        }

        LoggerProxy(String name, int level) {
            this.name = name;
            this.levelValue = level == 0 ? defaultLevel : level;
        }

        boolean isEnabled() {
            return levelValue != OFF;
        }

        int getLevel() {
            return effectiveLevel;
        }

        void setLevel(int newLevel) {
            levelValue = newLevel;
            effectiveLevel = newLevel;
        }

        void doLog(int level, String msg) {
            if (level < levelValue || levelValue == OFF) {
                return;
            }
            defaultStream.println(format(level, msg, null));
        }

        void doLog(int level, String msg, Throwable thrown) {
            if (level < levelValue || levelValue == OFF) {
                return;
            }
            defaultStream.println(format(level, msg, thrown));
        }

        void doLog(int level, String msg, Object... params) {
            if (level < levelValue || levelValue == OFF) {
                return;
            }
            String newMsg = formatMessage(msg, params);
            defaultStream.println(format(level, newMsg, null));
        }

        public boolean isLoggable(int level) {
            if (level < levelValue || levelValue == OFF) {
                return false;
            }
            return true;
        }

        private static final String format = "{0,date} {0,time}";

        private Object args[] = new Object[1];
        private MessageFormat formatter;
        private Date dat;

        // Copied from java.util.logging.Formatter.formatMessage
        private String formatMessage(String format, Object... parameters) {
            // Do the formatting.
            try {
                if (parameters == null || parameters.length == 0) {
                    // No parameters.  Just return format string.
                    return format;
                }
                // Is it a java.text style format?
                // Ideally we could match with
                // Pattern.compile("\\{\\d").matcher(format).find())
                // However the cost is 14% higher, so we cheaply check for
                // 1 of the first 4 parameters
                if (format.indexOf("{0") >= 0 || format.indexOf("{1") >=0 ||
                            format.indexOf("{2") >=0|| format.indexOf("{3") >=0) {
                    return java.text.MessageFormat.format(format, parameters);
                }
                return format;
            } catch (Exception ex) {
                // Formatting failed: use format string.
                return format;
            }
        }

        private synchronized String format(int level, String msg, Throwable thrown) {
            StringBuffer sb = new StringBuffer();
            // Minimize memory allocations here.
            if (dat == null) {
                dat = new Date();
                formatter = new MessageFormat(format);
            }
            dat.setTime(System.currentTimeMillis());
            args[0] = dat;
            StringBuffer text = new StringBuffer();
            formatter.format(args, text, null);
            sb.append(text);
            sb.append(" ");
            sb.append(getCallerInfo());
            sb.append(lineSeparator);
            sb.append(PlatformLogger.getLevelName(level));
            sb.append(": ");
            sb.append(msg);
            if (thrown != null) {
                try {
                    StringWriter sw = new StringWriter();
                    PrintWriter pw = new PrintWriter(sw);
                    thrown.printStackTrace(pw);
                    pw.close();
                    sb.append(sw.toString());
                } catch (Exception ex) {
                    throw new AssertionError(ex);
                }
            }

            return sb.toString();
        }

        // Returns the caller's class and method's name; best effort
        // if cannot infer, return the logger's name.
        private String getCallerInfo() {
            String sourceClassName = null;
            String sourceMethodName = null;

            JavaLangAccess access = SharedSecrets.getJavaLangAccess();
            Throwable throwable = new Throwable();
            int depth = access.getStackTraceDepth(throwable);

            String logClassName = "sun.util.logging.PlatformLogger";
            boolean lookingForLogger = true;
            for (int ix = 0; ix < depth; ix++) {
                // Calling getStackTraceElement directly prevents the VM
                // from paying the cost of building the entire stack frame.
                StackTraceElement frame =
                    access.getStackTraceElement(throwable, ix);
                String cname = frame.getClassName();
                if (lookingForLogger) {
                    // Skip all frames until we have found the first logger frame.
                    if (cname.equals(logClassName)) {
                        lookingForLogger = false;
                    }
                } else {
                    if (!cname.equals(logClassName)) {
                        // We've found the relevant frame.
                        sourceClassName = cname;
                        sourceMethodName = frame.getMethodName();
                        break;
                    }
                }
            }

            if (sourceClassName != null) {
                return sourceClassName + " " + sourceMethodName;
            } else {
                return name;
            }
        }
    }

    /**
     * JavaLogger forwards all the calls to its corresponding
     * java.util.logging.Logger object.
     */
    static class JavaLogger extends LoggerProxy {
        private static final boolean supported;
        private static final Class<?> loggerClass;
        private static final Class<?> levelClass;
        private static final Method getLoggerMethod;
        private static final Method setLevelMethod;
        private static final Method getLevelMethod;
        private static final Method logMethod;
        private static final Method logThrowMethod;
        private static final Method logParamsMethod;
        private static final Map<Integer, Object> levelObjects =
            new HashMap<Integer, Object>();

        static {
            loggerClass = getClass("java.util.logging.Logger");
            levelClass = getClass("java.util.logging.Level");
            getLoggerMethod = getMethod(loggerClass, "getLogger", String.class);
            setLevelMethod = getMethod(loggerClass, "setLevel", levelClass);
            getLevelMethod = getMethod(loggerClass, "getLevel");
            logMethod = getMethod(loggerClass, "log", levelClass, String.class);
            logThrowMethod = getMethod(loggerClass, "log", levelClass, String.class, Throwable.class);
            logParamsMethod = getMethod(loggerClass, "log", levelClass, String.class, Object[].class);
            supported = (loggerClass != null && levelClass != null && getLoggerMethod != null &&
                         getLevelMethod != null && setLevelMethod != null &&
                         logMethod != null && logThrowMethod != null && logParamsMethod != null);
            if (supported) {
                // initialize the map to Level objects
                getLevelObjects();
            }
        }

        private static Class<?> getClass(String name) {
            try {
                return Class.forName(name, true, null);
            } catch (ClassNotFoundException e) {
                return null;
            }
        }

        private static Method getMethod(Class<?> cls, String name, Class<?>... parameterTypes) {
            if (cls == null) return null;

            try {
                return cls.getMethod(name, parameterTypes);
            } catch (NoSuchMethodException e) {
                throw new AssertionError(e);
            }
        }

        private static Object invoke(Method m, Object obj, Object... params) {
            try {
                return m.invoke(obj, params);
            } catch (IllegalAccessException e) {
                throw new AssertionError(e);
            } catch (InvocationTargetException e) {
                throw new AssertionError(e);
            }
        }

        private static void getLevelObjects() {
            // get all java.util.logging.Level objects
            Method parseLevelMethod = getMethod(levelClass, "parse", String.class);
            int[] levelArray = new int[] {OFF, SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST, ALL};
            for (int l : levelArray) {
                Object o = invoke(parseLevelMethod, null, getLevelName(l));
                levelObjects.put(l, o);
            }
        }

        private final Object javaLogger;
        JavaLogger(String name) {
            this(name, 0);
        }

        JavaLogger(String name, int level) {
            super(name, level);
            this.javaLogger = invoke(getLoggerMethod, null, name);
            if (level != 0) {
                // level has been updated and so set the Logger's level
                invoke(setLevelMethod, javaLogger, levelObjects.get(level));
            }
        }

       /**
        * Let Logger.log() do the filtering since if the level of a
        * platform logger is altered directly from
        * java.util.logging.Logger.setLevel(), the levelValue will
        * not be updated.
        */
        void doLog(int level, String msg) {
            invoke(logMethod, javaLogger, levelObjects.get(level), msg);
        }

        void doLog(int level, String msg, Throwable t) {
            invoke(logThrowMethod, javaLogger, levelObjects.get(level), msg, t);
        }

        void doLog(int level, String msg, Object... params) {
            invoke(logParamsMethod, javaLogger, levelObjects.get(level), msg, params);
        }

        boolean isEnabled() {
            Object level = invoke(getLevelMethod, javaLogger);
            return level == null || level.equals(levelObjects.get(OFF)) == false;
        }

        int getLevel() {
            Object level = invoke(getLevelMethod, javaLogger);
            if (level != null) {
                for (Map.Entry<Integer, Object> l : levelObjects.entrySet()) {
                    if (level == l.getValue()) {
                        return l.getKey();
                    }
                }
            }
            return 0;
        }

        void setLevel(int newLevel) {
            levelValue = newLevel;
            invoke(setLevelMethod, javaLogger, levelObjects.get(newLevel));
        }
    }


    private static String getLevelName(int level) {
        switch (level) {
            case OFF     : return "OFF";
            case SEVERE  : return "SEVERE";
            case WARNING : return "WARNING";
            case INFO    : return "INFO";
            case CONFIG  : return "CONFIG";
            case FINE    : return "FINE";
            case FINER   : return "FINER";
            case FINEST  : return "FINEST";
            case ALL     : return "ALL";
            default      : return "UNKNOWN";
        }
    }

}