Expose hooks for more efficient log handling in Android apps.

This change introduces a new interface, DalvikLogHandler. Log
handlers that implement it opt-in to more efficient log handling
for common-case log messages. The API requires far fewer objects
to be allocated to log a message.

A related change in frameworks/base adopts this optimization
in the built-in AndroidHandler.

This optimization resulted in a 2.75x improvement on my device:
from 154ns to 56ns per message.
diff --git a/libcore/dalvik/src/main/java/dalvik/system/DalvikLogHandler.java b/libcore/dalvik/src/main/java/dalvik/system/DalvikLogHandler.java
new file mode 100644
index 0000000..a62ca3b
--- /dev/null
+++ b/libcore/dalvik/src/main/java/dalvik/system/DalvikLogHandler.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright (C) 2009 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package dalvik.system;
+
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ * An optimized handler for efficient publishing of basic log messages.
+ * Implementers should also be subclasses of {@link java.util.logging.Handler}.
+ *
+ * <p>Unlike the default log handler, this API doesn't require intermediate
+ * objects to be allocated for log handling. It also includes a short tag, which
+ * may otherwise need to be calculated for each published message.
+ *
+ * @hide
+ */
+public interface DalvikLogHandler {
+
+    /**
+     * Publishes a log message. Unlike {@link
+     * java.util.logging.Handler#publish(java.util.logging.LogRecord)}, this
+     * method includes only the raw log message. Log messages that were created
+     * with additional fields (parameters, source methods, etc.) will flow
+     * through the conventional channels instead.
+     *
+     * @param tag the short (23 characters or fewer) logger tag identifying
+     *      {@code logger}.
+     */
+    void publish(Logger source, String tag, Level level, String message);
+
+    // TODO: support messages with throwables?
+}
\ No newline at end of file
diff --git a/libcore/dalvik/src/main/java/dalvik/system/DalvikLogging.java b/libcore/dalvik/src/main/java/dalvik/system/DalvikLogging.java
new file mode 100644
index 0000000..b5c7ad5
--- /dev/null
+++ b/libcore/dalvik/src/main/java/dalvik/system/DalvikLogging.java
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2009 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package dalvik.system;
+
+/**
+ * Utility methods for logging to {@code DalvikHandlers}.
+ *
+ * @hide
+ */
+public final class DalvikLogging {
+    private DalvikLogging() {}
+
+    /**
+     * Returns the short logger tag (up to 23 chars) for the given logger name.
+     * Traditionally loggers are named by fully-qualified Java classes; this
+     * method attempts to return a concise identifying part of such names.
+     */
+    public static String loggerNameToTag(String loggerName) {
+        // Anonymous logger.
+        if (loggerName == null) {
+            return "null";
+        }
+
+        int length = loggerName.length();
+        if (length <= 23) {
+            return loggerName;
+        }
+
+        int lastPeriod = loggerName.lastIndexOf(".");
+        return length - (lastPeriod + 1) <= 23
+                ? loggerName.substring(lastPeriod + 1)
+                : loggerName.substring(loggerName.length() - 23);
+    }
+}
diff --git a/libcore/logging/src/main/java/java/util/logging/LogManager.java b/libcore/logging/src/main/java/java/util/logging/LogManager.java
index 378c926..d7ade24 100644
--- a/libcore/logging/src/main/java/java/util/logging/LogManager.java
+++ b/libcore/logging/src/main/java/java/util/logging/LogManager.java
@@ -484,7 +484,8 @@
         reset();
         props.load(ins);
 
-        // update handlers for the root logger only
+        // The RI treats the root logger as special. For compatibility, always
+        // update the root logger's handlers.
         Logger root = loggers.get("");
         if (root != null) {
             root.setManager(this);
@@ -623,6 +624,7 @@
             setLevelRecursively(logger, null);
         }
         newParent.children.add(logger);
+        logger.updateDalvikLogHandler(); // android-only
     }
 
     /**
diff --git a/libcore/logging/src/main/java/java/util/logging/Logger.java b/libcore/logging/src/main/java/java/util/logging/Logger.java
index c1870ca..e4f317d 100644
--- a/libcore/logging/src/main/java/java/util/logging/Logger.java
+++ b/libcore/logging/src/main/java/java/util/logging/Logger.java
@@ -20,13 +20,18 @@
 // BEGIN android-note
 // this file contains cleaned up documentation and style for contribution
 // upstream
+// It also contains Android-specific optimizations that aren't appropriate for
+// general purpose platforms
 // END android-note
 
+import dalvik.system.DalvikLogHandler;
+import dalvik.system.DalvikLogging;
 import org.apache.harmony.logging.internal.nls.Messages;
 
 import java.security.AccessController;
 import java.security.PrivilegedAction;
 import java.util.ArrayList;
+import java.util.Iterator;
 import java.util.List;
 import java.util.Locale;
 import java.util.MissingResourceException;
@@ -73,6 +78,18 @@
  */
 public class Logger {
 
+    // BEGIN android-only
+    /** A handler for use when no handler optimization is possible. */
+    private static final DalvikLogHandler GENERAL_LOG_HANDLER = new DalvikLogHandler() {
+        public void publish(Logger source, String tag, Level level, String message) {
+            LogRecord record = new LogRecord(level, message);
+            record.setLoggerName(source.name);
+            source.setResourceBundle(record);
+            source.log(record);
+        }
+    };
+    // END android-only
+
     /** The global logger is provided as convenience for casual use. */
     public final static Logger global = new Logger("global", null); //$NON-NLS-1$
 
@@ -137,6 +154,83 @@
      */
     final List<Logger> children = new ArrayList<Logger>();
 
+    // BEGIN android-only
+    /** the tag used for optimized logging. Derived from the logger name. */
+    private final String androidTag;
+
+    /** Handler delegate for either optimized or standard logging. */
+    private volatile DalvikLogHandler dalvikLogHandler = GENERAL_LOG_HANDLER;
+
+    /**
+     * We've optimized for the common case: logging to a single handler that
+     * implements {@link DalvikLogHandler}. This is how Android framework
+     * applications are configured by default.
+     *
+     * <p>This optimization has been measured to show a 2.75x improvement in
+     * throughput in the common case: 154ns vs. 56ns per message on a Cortex-A8.
+     * Direct use of {@code android.util.Log} takes 29ns per message.
+     *
+     * <p>Each time the handler configuration changes, either directly or
+     * indirectly, it's necessary to either turn on or off this optimization.
+     * When the optimization is off, {@link #dalvikLogHandler} is assigned to
+     * {@link #GENERAL_LOG_HANDLER} which can satisfy arbitrary configuration.
+     * When the optimization is possible, {@link #dalvikLogHandler} is assigned
+     * to the user's efficient implementation. In pratice this is usually the
+     * {@code com.android.internal.logging.AndroidHandler}.
+     */
+    void updateDalvikLogHandler() {
+        DalvikLogHandler newLogHandler = GENERAL_LOG_HANDLER;
+
+        Logger parent = this.parent;
+
+        if (getClass() != Logger.class) {
+            /*
+             * Do nothing. Subclasses aren't eligible for the optimization
+             * because they may override methods like getHandlers() or
+             * log(LogRecord).
+             */
+
+        } else if (parent == null) {
+            // we use an iterator rather than size()+get() for safe concurrency
+            Iterator<Handler> h = handlers.iterator();
+            if (h.hasNext()) {
+                Handler firstHandler = h.next();
+                if (!h.hasNext() && firstHandler instanceof DalvikLogHandler) {
+                    /*
+                     * At this point, we're eligible for the optimization. We've
+                     * satisfied these constraints:
+                     *   1. This is not a subclass of logger
+                     *   2. This is a root logger (no parent)
+                     *   3. There is exactly one handler installed
+                     *   4. That handler is a DalvikLogHandler
+                     */
+                    newLogHandler = (DalvikLogHandler) firstHandler;
+                }
+            }
+        } else if (handlers.isEmpty() && notifyParentHandlers) {
+            /*
+             * At this point, we're eligible for the optimization if our parent
+             * logger is eligible. We've satisfied these constraints:
+             *   1. This is not a subclass of logger
+             *   2. our parent exists
+             *   3. we have no handlers of our own
+             *   4. we notify our parent's handlers
+             */
+            newLogHandler = parent.dalvikLogHandler;
+        }
+
+        if (newLogHandler == this.dalvikLogHandler) {
+            return;
+        }
+
+        this.dalvikLogHandler = newLogHandler;
+
+        for (Logger logger : children) {
+            logger.updateDalvikLogHandler();
+        }
+    }
+    // END android-only
+
     /**
      * Constructs a {@code Logger} object with the supplied name and resource
      * bundle name; {@code notifiyParentHandlers} is set to {@code true}.
@@ -155,6 +249,10 @@
     protected Logger(String name, String resourceBundleName) {
         this.name = name;
         initResourceBundle(resourceBundleName);
+        // BEGIN android-only
+        this.androidTag = DalvikLogging.loggerNameToTag(name);
+        updateDalvikLogHandler();
+        // END android-only
     }
 
     /**
@@ -349,6 +447,7 @@
             LogManager.getLogManager().checkAccess();
         }
         this.handlers.add(handler);
+        updateDalvikLogHandler(); // android-only
     }
 
     /**
@@ -394,6 +493,8 @@
                 handlers.add(handler);
             }
         }
+
+        updateDalvikLogHandler(); // android-only
     }
 
     /**
@@ -424,6 +525,7 @@
             return;
         }
         this.handlers.remove(handler);
+        updateDalvikLogHandler(); // android-only
     }
 
     /**
@@ -509,6 +611,7 @@
             LogManager.getLogManager().checkAccess();
         }
         this.notifyParentHandlers = notifyParentHandlers;
+        updateDalvikLogHandler(); // android-only
     }
 
     /**
@@ -875,10 +978,9 @@
             return;
         }
 
-        LogRecord record = new LogRecord(logLevel, msg);
-        record.setLoggerName(this.name);
-        setResourceBundle(record);
-        log(record);
+        // BEGIN android-only
+        dalvikLogHandler.publish(this, androidTag, logLevel, msg);
+        // END android-only
     }
 
     /**
@@ -1296,5 +1398,7 @@
             } catch (Exception ignored) {
             }
         }
+
+        updateDalvikLogHandler(); // android-only
     }
 }