You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@logging.apache.org by rp...@apache.org on 2015/10/22 19:56:29 UTC

[01/14] logging-log4j2 git commit: LOG4J2-493 AsyncLoggerContextSelector no longer has a singleton context, but manages multiple contexts (max one per classloader)

Repository: logging-log4j2
Updated Branches:
  refs/heads/master 2a853aa87 -> 7ffd4cfe1


LOG4J2-493 AsyncLoggerContextSelector no longer has a singleton context,
but manages multiple contexts (max one per classloader)


Project: http://git-wip-us.apache.org/repos/asf/logging-log4j2/repo
Commit: http://git-wip-us.apache.org/repos/asf/logging-log4j2/commit/7e6c1b22
Tree: http://git-wip-us.apache.org/repos/asf/logging-log4j2/tree/7e6c1b22
Diff: http://git-wip-us.apache.org/repos/asf/logging-log4j2/diff/7e6c1b22

Branch: refs/heads/master
Commit: 7e6c1b2270760798f4014e8ea5e1fa84843f26c9
Parents: 2a853aa
Author: rpopma <rp...@apache.org>
Authored: Thu Oct 22 10:34:20 2015 +0900
Committer: rpopma <rp...@apache.org>
Committed: Thu Oct 22 10:34:20 2015 +0900

----------------------------------------------------------------------
 .../core/async/AsyncLoggerContextSelector.java  | 24 ++++++++++++--------
 1 file changed, 15 insertions(+), 9 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/7e6c1b22/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLoggerContextSelector.java
----------------------------------------------------------------------
diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLoggerContextSelector.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLoggerContextSelector.java
index 83e644c..d2ee058 100644
--- a/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLoggerContextSelector.java
+++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLoggerContextSelector.java
@@ -18,8 +18,9 @@ package org.apache.logging.log4j.core.async;
 
 import java.net.URI;
 import java.util.ArrayList;
-import java.util.Collections;
 import java.util.List;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
 
 import org.apache.logging.log4j.core.LoggerContext;
 import org.apache.logging.log4j.core.selector.ContextSelector;
@@ -31,9 +32,7 @@ import org.apache.logging.log4j.util.PropertiesUtil;
  */
 public class AsyncLoggerContextSelector implements ContextSelector {
 
-    // LOG4J2-666 ensure unique name across separate instances created by webapp classloaders
-    private static final AsyncLoggerContext CONTEXT = new AsyncLoggerContext("AsyncLoggerContext@"
-            + Integer.toHexString(AsyncLoggerContext.class.hashCode()));
+    private ConcurrentMap<String, AsyncLoggerContext> contexts = new ConcurrentHashMap<String, AsyncLoggerContext>();
 
     /**
      * Returns {@code true} if the user specified this selector as the Log4jContextSelector, to make all loggers
@@ -48,24 +47,31 @@ public class AsyncLoggerContextSelector implements ContextSelector {
 
     @Override
     public LoggerContext getContext(final String fqcn, final ClassLoader loader, final boolean currentContext) {
-        return CONTEXT;
+        // LOG4J2-666 ensure unique name across separate instances created by webapp classloaders
+        final int hash = loader == null ? getClass().getClassLoader().hashCode() : loader.hashCode();
+        final String key = "AsyncLoggerContext@" + Integer.toHexString(hash);
+        AsyncLoggerContext result = contexts.get(key);
+        if (result == null) {
+            result = new AsyncLoggerContext(key);
+            return contexts.putIfAbsent(key, result);
+        }
+        return result;
     }
 
     @Override
     public List<LoggerContext> getLoggerContexts() {
-        final List<LoggerContext> list = new ArrayList<>();
-        list.add(CONTEXT);
-        return Collections.unmodifiableList(list);
+        return new ArrayList<LoggerContext>(contexts.values());
     }
 
     @Override
     public LoggerContext getContext(final String fqcn, final ClassLoader loader, final boolean currentContext,
             final URI configLocation) {
-        return CONTEXT;
+        return getContext(fqcn, loader, currentContext);
     }
 
     @Override
     public void removeContext(final LoggerContext context) {
+        contexts.remove(context.getName());
     }
 
 }


[02/14] logging-log4j2 git commit: LOG4J2-493 allow for multiple, distinct AsyncLoggerHelper instances

Posted by rp...@apache.org.
LOG4J2-493 allow for multiple, distinct AsyncLoggerHelper instances

- Disruptor and Executor are now non-static fields in AsyncLoggerHelper
- converted all static methods to non-static methods

Project: http://git-wip-us.apache.org/repos/asf/logging-log4j2/repo
Commit: http://git-wip-us.apache.org/repos/asf/logging-log4j2/commit/586920b4
Tree: http://git-wip-us.apache.org/repos/asf/logging-log4j2/tree/586920b4
Diff: http://git-wip-us.apache.org/repos/asf/logging-log4j2/diff/586920b4

Branch: refs/heads/master
Commit: 586920b47cc4f656ab9fa5f7584e1d72cc9bdf1a
Parents: 7e6c1b2
Author: rpopma <rp...@apache.org>
Authored: Thu Oct 22 10:35:43 2015 +0900
Committer: rpopma <rp...@apache.org>
Committed: Thu Oct 22 10:35:43 2015 +0900

----------------------------------------------------------------------
 .../log4j/core/async/AsyncLoggerHelper.java     | 30 ++++++++++----------
 1 file changed, 15 insertions(+), 15 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/586920b4/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLoggerHelper.java
----------------------------------------------------------------------
diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLoggerHelper.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLoggerHelper.java
index 43dacc1..33a34e1 100644
--- a/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLoggerHelper.java
+++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLoggerHelper.java
@@ -39,8 +39,8 @@ import com.lmax.disruptor.dsl.ProducerType;
  * Helper class for AsyncLogger:
  * <ul>
  * <li>Separates the AsyncLogger business logic (logging) from the mechanics of working with the LMAX Disruptor.</li>
- * <li>Disruptor initialization no longer happens in a static initializer block in AsyncLogger to prevent problems where
- * the Disruptor is unintentionally initialized (and a thread started) because a static method in AsyncLogger is called
+ * <li>Disruptor initialization no longer happens in a initializer block in AsyncLogger to prevent problems where
+ * the Disruptor is unintentionally initialized (and a thread started) because a method in AsyncLogger is called
  * (LOG4J2-1159).</li>
  * <li>Enable a reference counting scheme tracking the total number of starts and stops, so the Disruptor and associated
  * Executor can be shut down when usage becomes zero. This fixes a long-standing issue that made AsyncLoggers unsuitable
@@ -54,11 +54,11 @@ public class AsyncLoggerHelper {
     private static final int RINGBUFFER_DEFAULT_SIZE = 256 * 1024;
     private static final StatusLogger LOGGER = StatusLogger.getLogger();
 
-    private static ExecutorService executor;
-    private static volatile Disruptor<RingBufferLogEvent> disruptor;
-    private static volatile int count = 0;
+    private ExecutorService executor;
+    private volatile Disruptor<RingBufferLogEvent> disruptor;
+    private volatile int count = 0;
 
-    static Disruptor<RingBufferLogEvent> getDisruptor() {
+    Disruptor<RingBufferLogEvent> getDisruptor() {
         return disruptor;
     }
 
@@ -68,12 +68,12 @@ public class AsyncLoggerHelper {
      * 
      * @see #release()
      */
-    static synchronized void start() {
+    synchronized void start() {
         count++;
         initDisruptor();
     }
 
-    private static synchronized void initDisruptor() {
+    private synchronized void initDisruptor() {
         if (disruptor != null) {
             LOGGER.trace("AsyncLoggerHelper not starting new disruptor, using existing object. Ref count is {}.", count);
             return;
@@ -96,7 +96,7 @@ public class AsyncLoggerHelper {
         disruptor.start();
     }
 
-    private static int calculateRingBufferSize() {
+    private int calculateRingBufferSize() {
         int ringBufferSize = RINGBUFFER_DEFAULT_SIZE;
         final String userPreferredRBSize = PropertiesUtil.getProperties().getStringProperty(
                 "AsyncLogger.RingBufferSize", String.valueOf(ringBufferSize));
@@ -114,7 +114,7 @@ public class AsyncLoggerHelper {
         return Integers.ceilingNextPowerOfTwo(ringBufferSize);
     }
 
-    private static WaitStrategy createWaitStrategy() {
+    private WaitStrategy createWaitStrategy() {
         final String strategy = PropertiesUtil.getProperties().getStringProperty("AsyncLogger.WaitStrategy");
         LOGGER.debug("property AsyncLogger.WaitStrategy={}", strategy);
         if ("Sleep".equals(strategy)) {
@@ -128,7 +128,7 @@ public class AsyncLoggerHelper {
         return new BlockingWaitStrategy();
     }
 
-    private static ExceptionHandler<RingBufferLogEvent> getExceptionHandler() {
+    private ExceptionHandler<RingBufferLogEvent> getExceptionHandler() {
         final String cls = PropertiesUtil.getProperties().getStringProperty("AsyncLogger.ExceptionHandler");
         if (cls == null) {
             LOGGER.debug("No AsyncLogger.ExceptionHandler specified");
@@ -146,7 +146,7 @@ public class AsyncLoggerHelper {
         }
     }
 
-    static void enqueueLogMessageInfo(final RingBufferLogEventTranslator translator) {
+    void enqueueLogMessageInfo(final RingBufferLogEventTranslator translator) {
         // LOG4J2-639: catch NPE if disruptor field was set to null in release()
         try {
             // Note: we deliberately access the volatile disruptor field afresh here.
@@ -164,7 +164,7 @@ public class AsyncLoggerHelper {
      * @param contextName name of the global {@code AsyncLoggerContext}
      * @return a new {@code RingBufferAdmin} that instruments the ringbuffer
      */
-    public static RingBufferAdmin createRingBufferAdmin(final String contextName) {
+    public RingBufferAdmin createRingBufferAdmin(final String contextName) {
         return RingBufferAdmin.forAsyncLogger(disruptor.getRingBuffer(), contextName);
     }
 
@@ -172,7 +172,7 @@ public class AsyncLoggerHelper {
      * Decreases the reference count. If the reference count reached zero, the Disruptor and its associated thread are
      * shut down and their references set to {@code null}.
      */
-    static synchronized void stop() {
+    synchronized void stop() {
         if (--count > 0) {
             LOGGER.trace("AsyncLoggerHelper: not shutting down disruptor: ref count is {}.", count);
             return;
@@ -210,7 +210,7 @@ public class AsyncLoggerHelper {
     /**
      * Returns {@code true} if the specified disruptor still has unprocessed events.
      */
-    private static boolean hasBacklog(final Disruptor<?> theDisruptor) {
+    private boolean hasBacklog(final Disruptor<?> theDisruptor) {
         final RingBuffer<?> ringBuffer = theDisruptor.getRingBuffer();
         return !ringBuffer.hasAvailableCapacity(ringBuffer.getBufferSize());
     }


[03/14] logging-log4j2 git commit: LOG4J2-493 AsyncLoggerContext now has an AsyncLoggerHelper field, essentially managing one Disruptor/Executor per context

Posted by rp...@apache.org.
LOG4J2-493 AsyncLoggerContext now has an AsyncLoggerHelper field,
essentially managing one Disruptor/Executor per context


Project: http://git-wip-us.apache.org/repos/asf/logging-log4j2/repo
Commit: http://git-wip-us.apache.org/repos/asf/logging-log4j2/commit/12f90a9f
Tree: http://git-wip-us.apache.org/repos/asf/logging-log4j2/tree/12f90a9f
Diff: http://git-wip-us.apache.org/repos/asf/logging-log4j2/diff/12f90a9f

Branch: refs/heads/master
Commit: 12f90a9f1f615b3bfb0bdc104698b1495eab0e20
Parents: 586920b
Author: rpopma <rp...@apache.org>
Authored: Thu Oct 22 10:36:37 2015 +0900
Committer: rpopma <rp...@apache.org>
Committed: Thu Oct 22 10:36:37 2015 +0900

----------------------------------------------------------------------
 .../log4j/core/async/AsyncLoggerContext.java    | 26 +++++++++++++++++---
 1 file changed, 22 insertions(+), 4 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/12f90a9f/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLoggerContext.java
----------------------------------------------------------------------
diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLoggerContext.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLoggerContext.java
index 44bc41f..f9e707b 100644
--- a/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLoggerContext.java
+++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLoggerContext.java
@@ -21,6 +21,7 @@ import java.net.URI;
 import org.apache.logging.log4j.core.Logger;
 import org.apache.logging.log4j.core.LoggerContext;
 import org.apache.logging.log4j.core.config.Configuration;
+import org.apache.logging.log4j.core.jmx.RingBufferAdmin;
 import org.apache.logging.log4j.message.MessageFactory;
 
 /**
@@ -29,29 +30,35 @@ import org.apache.logging.log4j.message.MessageFactory;
 public class AsyncLoggerContext extends LoggerContext {
 
     private static final long serialVersionUID = 1L;
+    
+    private final AsyncLoggerHelper helper;
 
     public AsyncLoggerContext(final String name) {
         super(name);
+        helper = new AsyncLoggerHelper();
     }
 
     public AsyncLoggerContext(final String name, final Object externalContext) {
         super(name, externalContext);
+        helper = new AsyncLoggerHelper();
     }
 
     public AsyncLoggerContext(final String name, final Object externalContext,
             final URI configLocn) {
         super(name, externalContext, configLocn);
+        helper = new AsyncLoggerHelper();
     }
 
     public AsyncLoggerContext(final String name, final Object externalContext,
             final String configLocn) {
         super(name, externalContext, configLocn);
+        helper = new AsyncLoggerHelper();
     }
 
     @Override
     protected Logger newInstance(final LoggerContext ctx, final String name,
             final MessageFactory messageFactory) {
-        return new AsyncLogger(ctx, name, messageFactory);
+        return new AsyncLogger(ctx, name, messageFactory, helper);
     }
 
     /* (non-Javadoc)
@@ -59,7 +66,7 @@ public class AsyncLoggerContext extends LoggerContext {
      */
     @Override
     public void start() {
-        AsyncLoggerHelper.start();
+        helper.start();
         super.start();
     }
 
@@ -68,13 +75,24 @@ public class AsyncLoggerContext extends LoggerContext {
      */
     @Override
     public void start(Configuration config) {
-        AsyncLoggerHelper.start();
+        helper.start();
         super.start(config);
     }
 
     @Override
     public void stop() {
-        AsyncLoggerHelper.stop(); // first stop Disruptor
+        helper.stop(); // first stop Disruptor
         super.stop();
     }
+
+    /**
+     * Creates and returns a new {@code RingBufferAdmin} that instruments the ringbuffer of the {@code AsyncLogger}
+     * objects.
+     *
+     * @param contextName name of this {@code AsyncLoggerContext}
+     * @return a new {@code RingBufferAdmin} that instruments the ringbuffer
+     */
+    public RingBufferAdmin createRingBufferAdmin() {
+        return helper.createRingBufferAdmin(getName());
+    }
 }


[08/14] logging-log4j2 git commit: LOG4J2-493 removed obsolete counter, improved status logging

Posted by rp...@apache.org.
LOG4J2-493 removed obsolete counter, improved status logging

Project: http://git-wip-us.apache.org/repos/asf/logging-log4j2/repo
Commit: http://git-wip-us.apache.org/repos/asf/logging-log4j2/commit/25fe68d2
Tree: http://git-wip-us.apache.org/repos/asf/logging-log4j2/tree/25fe68d2
Diff: http://git-wip-us.apache.org/repos/asf/logging-log4j2/diff/25fe68d2

Branch: refs/heads/master
Commit: 25fe68d2de481d66b4dd26ac67ecdb6f2f72e4d7
Parents: 6e45177
Author: rpopma <rp...@apache.org>
Authored: Fri Oct 23 02:15:08 2015 +0900
Committer: rpopma <rp...@apache.org>
Committed: Fri Oct 23 02:15:08 2015 +0900

----------------------------------------------------------------------
 .../log4j/core/async/AsyncLoggerHelper.java     | 78 +++++++++-----------
 1 file changed, 35 insertions(+), 43 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/25fe68d2/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLoggerHelper.java
----------------------------------------------------------------------
diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLoggerHelper.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLoggerHelper.java
index 33a34e1..027fa0d 100644
--- a/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLoggerHelper.java
+++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLoggerHelper.java
@@ -36,16 +36,10 @@ import com.lmax.disruptor.dsl.Disruptor;
 import com.lmax.disruptor.dsl.ProducerType;
 
 /**
- * Helper class for AsyncLogger:
- * <ul>
- * <li>Separates the AsyncLogger business logic (logging) from the mechanics of working with the LMAX Disruptor.</li>
- * <li>Disruptor initialization no longer happens in a initializer block in AsyncLogger to prevent problems where
- * the Disruptor is unintentionally initialized (and a thread started) because a method in AsyncLogger is called
- * (LOG4J2-1159).</li>
- * <li>Enable a reference counting scheme tracking the total number of starts and stops, so the Disruptor and associated
- * Executor can be shut down when usage becomes zero. This fixes a long-standing issue that made AsyncLoggers unsuitable
- * for use in web applications (LOG4J2-493).</li>
- * </ul>
+ * Helper class for async loggers: AsyncLoggerHelper handles the mechanics of working with the LMAX Disruptor, and
+ * works with its associated AsyncLoggerContext to synchronize the life cycle of the Disruptor and its thread with the
+ * life cycle of the context. The AsyncLoggerHelper of the context is shared by all AsyncLogger objects created by that
+ * AsyncLoggerContext.
  */
 public class AsyncLoggerHelper {
     private static final int SLEEP_MILLIS_BETWEEN_DRAIN_ATTEMPTS = 50;
@@ -54,34 +48,36 @@ public class AsyncLoggerHelper {
     private static final int RINGBUFFER_DEFAULT_SIZE = 256 * 1024;
     private static final StatusLogger LOGGER = StatusLogger.getLogger();
 
+    private final String contextName;
     private ExecutorService executor;
     private volatile Disruptor<RingBufferLogEvent> disruptor;
-    private volatile int count = 0;
+
+    public AsyncLoggerHelper(String contextName) {
+        this.contextName = contextName;
+    }
+
+    public String getContextName() {
+        return contextName;
+    }
 
     Disruptor<RingBufferLogEvent> getDisruptor() {
         return disruptor;
     }
 
     /**
-     * Increases the reference count and creates and starts a new Disruptor and associated thread if none currently
-     * exists.
+     * Creates and starts a new Disruptor and associated thread if none currently exists.
      * 
-     * @see #release()
+     * @see #stop()
      */
     synchronized void start() {
-        count++;
-        initDisruptor();
-    }
-
-    private synchronized void initDisruptor() {
         if (disruptor != null) {
-            LOGGER.trace("AsyncLoggerHelper not starting new disruptor, using existing object. Ref count is {}.", count);
+            LOGGER.trace("[{}] AsyncLoggerHelper not starting new disruptor, using existing object.", contextName);
             return;
         }
-        LOGGER.trace("AsyncLoggerHelper creating new disruptor. Ref count is {}.", count);
+        LOGGER.trace("[{}] AsyncLoggerHelper creating new disruptor.", contextName);
         final int ringBufferSize = calculateRingBufferSize();
         final WaitStrategy waitStrategy = createWaitStrategy();
-        executor = Executors.newSingleThreadExecutor(new DaemonThreadFactory("AsyncLogger-"));
+        executor = Executors.newSingleThreadExecutor(new DaemonThreadFactory(contextName + "-Logger-"));
         Info.initExecutorThreadInstance(executor);
 
         disruptor = new Disruptor<>(RingBufferLogEvent.FACTORY, ringBufferSize, executor, ProducerType.MULTI,
@@ -91,8 +87,8 @@ public class AsyncLoggerHelper {
         final RingBufferLogEventHandler[] handlers = {new RingBufferLogEventHandler()};
         disruptor.handleEventsWith(handlers);
 
-        LOGGER.debug("Starting AsyncLogger disruptor with ringbuffer size {}...", disruptor.getRingBuffer()
-                .getBufferSize());
+        LOGGER.debug("[{}] Starting AsyncLogger disruptor with ringbuffer size {}...", contextName, disruptor
+                .getRingBuffer().getBufferSize());
         disruptor.start();
     }
 
@@ -104,19 +100,20 @@ public class AsyncLoggerHelper {
             int size = Integer.parseInt(userPreferredRBSize);
             if (size < RINGBUFFER_MIN_SIZE) {
                 size = RINGBUFFER_MIN_SIZE;
-                LOGGER.warn("Invalid RingBufferSize {}, using minimum size {}.", userPreferredRBSize,
+                LOGGER.warn("[{}] Invalid RingBufferSize {}, using minimum size {}.", contextName, userPreferredRBSize,
                         RINGBUFFER_MIN_SIZE);
             }
             ringBufferSize = size;
         } catch (final Exception ex) {
-            LOGGER.warn("Invalid RingBufferSize {}, using default size {}.", userPreferredRBSize, ringBufferSize);
+            LOGGER.warn("[{}] Invalid RingBufferSize {}, using default size {}.", contextName, userPreferredRBSize,
+                    ringBufferSize);
         }
         return Integers.ceilingNextPowerOfTwo(ringBufferSize);
     }
 
     private WaitStrategy createWaitStrategy() {
         final String strategy = PropertiesUtil.getProperties().getStringProperty("AsyncLogger.WaitStrategy");
-        LOGGER.debug("property AsyncLogger.WaitStrategy={}", strategy);
+        LOGGER.debug("[{}] property AsyncLogger.WaitStrategy={}", contextName, strategy);
         if ("Sleep".equals(strategy)) {
             return new SleepingWaitStrategy();
         } else if ("Yield".equals(strategy)) {
@@ -124,24 +121,25 @@ public class AsyncLoggerHelper {
         } else if ("Block".equals(strategy)) {
             return new BlockingWaitStrategy();
         }
-        LOGGER.debug("disruptor event handler uses BlockingWaitStrategy");
+        LOGGER.debug("[{}] disruptor event handler uses BlockingWaitStrategy", contextName);
         return new BlockingWaitStrategy();
     }
 
     private ExceptionHandler<RingBufferLogEvent> getExceptionHandler() {
         final String cls = PropertiesUtil.getProperties().getStringProperty("AsyncLogger.ExceptionHandler");
         if (cls == null) {
-            LOGGER.debug("No AsyncLogger.ExceptionHandler specified");
+            LOGGER.debug("[{}] No AsyncLogger.ExceptionHandler specified", contextName);
             return null;
         }
         try {
             @SuppressWarnings("unchecked")
             final ExceptionHandler<RingBufferLogEvent> result = Loader
                     .newCheckedInstanceOf(cls, ExceptionHandler.class);
-            LOGGER.debug("AsyncLogger.ExceptionHandler={}", result);
+            LOGGER.debug("[{}] AsyncLogger.ExceptionHandler={}", contextName, result);
             return result;
         } catch (final Exception ignored) {
-            LOGGER.debug("AsyncLogger.ExceptionHandler not set: error creating " + cls + ": ", ignored);
+            LOGGER.debug("[{}] AsyncLogger.ExceptionHandler not set: error creating " + cls + ": ", contextName,
+                    ignored);
             return null;
         }
     }
@@ -150,11 +148,11 @@ public class AsyncLoggerHelper {
         // LOG4J2-639: catch NPE if disruptor field was set to null in release()
         try {
             // Note: we deliberately access the volatile disruptor field afresh here.
-            // Avoiding this and using an older refrence could result in adding a log event to the disruptor after it
+            // Avoiding this and using an older reference could result in adding a log event to the disruptor after it
             // was shut down, which could cause the publishEvent method to hang and never return.
             disruptor.publishEvent(translator);
         } catch (final NullPointerException npe) {
-            LOGGER.fatal("Ignoring log event after log4j was shut down.");
+            LOGGER.fatal("[{}] Ignoring log event after log4j was shut down.", contextName);
         }
     }
 
@@ -173,18 +171,12 @@ public class AsyncLoggerHelper {
      * shut down and their references set to {@code null}.
      */
     synchronized void stop() {
-        if (--count > 0) {
-            LOGGER.trace("AsyncLoggerHelper: not shutting down disruptor: ref count is {}.", count);
-            return;
-        }
-
         final Disruptor<RingBufferLogEvent> temp = getDisruptor();
         if (temp == null) {
-            LOGGER.trace("AsyncLoggerHelper: disruptor already shut down: ref count is {}. (Resetting to zero.)", count);
-            count = 0; // ref count must not be negative or #claim() will not work correctly
+            LOGGER.trace("[{}] AsyncLoggerHelper: disruptor already shut down.", contextName);
             return; // disruptor was already shut down by another thread
         }
-        LOGGER.debug("AsyncLoggerHelper: shutting down disruptor: ref count is {}.", count);
+        LOGGER.debug("[{}] AsyncLoggerHelper: shutting down disruptor.", contextName);
 
         // Must guarantee that publishing to the RingBuffer has stopped
         // before we call disruptor.shutdown()
@@ -201,7 +193,7 @@ public class AsyncLoggerHelper {
         }
         temp.shutdown(); // busy-spins until all events currently in the disruptor have been processed
 
-        LOGGER.trace("AsyncLoggerHelper: shutting down disruptor executor.");
+        LOGGER.trace("[{}] AsyncLoggerHelper: shutting down disruptor executor.", contextName);
         executor.shutdown(); // finally, kill the processor thread
         executor = null;
         // Info.THREADLOCAL.remove(); // LOG4J2-323
@@ -210,7 +202,7 @@ public class AsyncLoggerHelper {
     /**
      * Returns {@code true} if the specified disruptor still has unprocessed events.
      */
-    private boolean hasBacklog(final Disruptor<?> theDisruptor) {
+    private static boolean hasBacklog(final Disruptor<?> theDisruptor) {
         final RingBuffer<?> ringBuffer = theDisruptor.getRingBuffer();
         return !ringBuffer.hasAvailableCapacity(ringBuffer.getBufferSize());
     }


[10/14] logging-log4j2 git commit: LOG4J2-493 subclass ClassLoaderContextSelector

Posted by rp...@apache.org.
LOG4J2-493 subclass ClassLoaderContextSelector

Project: http://git-wip-us.apache.org/repos/asf/logging-log4j2/repo
Commit: http://git-wip-us.apache.org/repos/asf/logging-log4j2/commit/3705a75d
Tree: http://git-wip-us.apache.org/repos/asf/logging-log4j2/tree/3705a75d
Diff: http://git-wip-us.apache.org/repos/asf/logging-log4j2/diff/3705a75d

Branch: refs/heads/master
Commit: 3705a75d173d489b2caa7d053b9d4f27632ebef7
Parents: 7800b8f
Author: rpopma <rp...@apache.org>
Authored: Fri Oct 23 02:19:42 2015 +0900
Committer: rpopma <rp...@apache.org>
Committed: Fri Oct 23 02:19:42 2015 +0900

----------------------------------------------------------------------
 .../core/async/AsyncLoggerContextSelector.java  | 43 +++++---------------
 1 file changed, 10 insertions(+), 33 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/3705a75d/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLoggerContextSelector.java
----------------------------------------------------------------------
diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLoggerContextSelector.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLoggerContextSelector.java
index d2ee058..4d739e3 100644
--- a/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLoggerContextSelector.java
+++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLoggerContextSelector.java
@@ -17,22 +17,16 @@
 package org.apache.logging.log4j.core.async;
 
 import java.net.URI;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
 
 import org.apache.logging.log4j.core.LoggerContext;
-import org.apache.logging.log4j.core.selector.ContextSelector;
+import org.apache.logging.log4j.core.selector.ClassLoaderContextSelector;
 import org.apache.logging.log4j.core.util.Constants;
 import org.apache.logging.log4j.util.PropertiesUtil;
 
 /**
- * {@code ContextSelector} that returns the singleton {@code AsyncLoggerContext}.
+ * {@code ContextSelector} that manages {@code AsyncLoggerContext} instances.
  */
-public class AsyncLoggerContextSelector implements ContextSelector {
-
-    private ConcurrentMap<String, AsyncLoggerContext> contexts = new ConcurrentHashMap<String, AsyncLoggerContext>();
+public class AsyncLoggerContextSelector extends ClassLoaderContextSelector {
 
     /**
      * Returns {@code true} if the user specified this selector as the Log4jContextSelector, to make all loggers
@@ -45,33 +39,16 @@ public class AsyncLoggerContextSelector implements ContextSelector {
                 PropertiesUtil.getProperties().getStringProperty(Constants.LOG4J_CONTEXT_SELECTOR));
     }
 
-    @Override
-    public LoggerContext getContext(final String fqcn, final ClassLoader loader, final boolean currentContext) {
-        // LOG4J2-666 ensure unique name across separate instances created by webapp classloaders
-        final int hash = loader == null ? getClass().getClassLoader().hashCode() : loader.hashCode();
-        final String key = "AsyncLoggerContext@" + Integer.toHexString(hash);
-        AsyncLoggerContext result = contexts.get(key);
-        if (result == null) {
-            result = new AsyncLoggerContext(key);
-            return contexts.putIfAbsent(key, result);
-        }
-        return result;
-    }
-
-    @Override
-    public List<LoggerContext> getLoggerContexts() {
-        return new ArrayList<LoggerContext>(contexts.values());
+    protected LoggerContext createContext(final String name, final URI configLocation) {
+        return new AsyncLoggerContext(name, null, configLocation);
     }
 
-    @Override
-    public LoggerContext getContext(final String fqcn, final ClassLoader loader, final boolean currentContext,
-            final URI configLocation) {
-        return getContext(fqcn, loader, currentContext);
+    protected String toContextMapKey(final ClassLoader loader) {
+        // LOG4J2-666 ensure unique name across separate instances created by webapp classloaders
+        return "AsyncContext@" + Integer.toHexString(System.identityHashCode(loader));
     }
 
-    @Override
-    public void removeContext(final LoggerContext context) {
-        contexts.remove(context.getName());
+    protected String defaultContextName() {
+        return "DefaultAsyncContext@" + Thread.currentThread().getName();
     }
-
 }


[13/14] logging-log4j2 git commit: LOG4J2-493 fixed tests: AsyncLoggerContext is no longer a singleton

Posted by rp...@apache.org.
LOG4J2-493 fixed tests: AsyncLoggerContext is no longer a singleton

Project: http://git-wip-us.apache.org/repos/asf/logging-log4j2/repo
Commit: http://git-wip-us.apache.org/repos/asf/logging-log4j2/commit/4b0b01dd
Tree: http://git-wip-us.apache.org/repos/asf/logging-log4j2/tree/4b0b01dd
Diff: http://git-wip-us.apache.org/repos/asf/logging-log4j2/diff/4b0b01dd

Branch: refs/heads/master
Commit: 4b0b01ddac5e26905b1a45c5c1086f32fb6c8b91
Parents: 6659d55
Author: rpopma <rp...@apache.org>
Authored: Fri Oct 23 02:25:53 2015 +0900
Committer: rpopma <rp...@apache.org>
Committed: Fri Oct 23 02:25:53 2015 +0900

----------------------------------------------------------------------
 .../core/async/AsyncLoggerContextSelectorTest.java      | 12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/4b0b01dd/log4j-core/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerContextSelectorTest.java
----------------------------------------------------------------------
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerContextSelectorTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerContextSelectorTest.java
index 3bae290..23c4cdd 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerContextSelectorTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerContextSelectorTest.java
@@ -42,10 +42,17 @@ public class AsyncLoggerContextSelectorTest {
     }
 
     @Test
+    public void testLoggerContextsListInitiallyEmpty() {
+        final AsyncLoggerContextSelector selector = new AsyncLoggerContextSelector();
+        assertTrue(selector.getLoggerContexts().isEmpty());
+    }
+
+    @Test
     public void testLoggerContextsReturnsAsyncLoggerContext() {
         final AsyncLoggerContextSelector selector = new AsyncLoggerContextSelector();
-        final List<LoggerContext> list = selector.getLoggerContexts();
+        selector.getContext(null, null, false);
 
+        final List<LoggerContext> list = selector.getLoggerContexts();
         assertEquals(1, list.size());
         assertTrue(list.get(0) instanceof AsyncLoggerContext);
     }
@@ -54,7 +61,8 @@ public class AsyncLoggerContextSelectorTest {
     public void testContextNameIsAsyncLoggerContextWithClassHashCode() {
         final AsyncLoggerContextSelector selector = new AsyncLoggerContextSelector();
         final LoggerContext context = selector.getContext(null, null, false);
-        final String expectedContextName = "AsyncLoggerContext@" + Integer.toHexString(AsyncLoggerContext.class.hashCode());
+        final int hash = getClass().getClassLoader().hashCode();
+        final String expectedContextName = "AsyncLoggerContext@" + Integer.toHexString(hash);
         assertEquals(expectedContextName, context.getName());
     }
 


[05/14] logging-log4j2 git commit: LOG4J2-493 changes to JMX RingBuffer MBean because AsyncLoggerContext is no longer static

Posted by rp...@apache.org.
LOG4J2-493 changes to JMX RingBuffer MBean because AsyncLoggerContext is
no longer static

Project: http://git-wip-us.apache.org/repos/asf/logging-log4j2/repo
Commit: http://git-wip-us.apache.org/repos/asf/logging-log4j2/commit/3195cdac
Tree: http://git-wip-us.apache.org/repos/asf/logging-log4j2/tree/3195cdac
Diff: http://git-wip-us.apache.org/repos/asf/logging-log4j2/diff/3195cdac

Branch: refs/heads/master
Commit: 3195cdac52d7f964d5fc962b7753f4371e7fd0c7
Parents: dc62934
Author: rpopma <rp...@apache.org>
Authored: Thu Oct 22 10:38:25 2015 +0900
Committer: rpopma <rp...@apache.org>
Committed: Thu Oct 22 10:38:25 2015 +0900

----------------------------------------------------------------------
 .../src/main/java/org/apache/logging/log4j/core/jmx/Server.java    | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/3195cdac/log4j-core/src/main/java/org/apache/logging/log4j/core/jmx/Server.java
----------------------------------------------------------------------
diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/jmx/Server.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/jmx/Server.java
index 4860551..b3f4614 100644
--- a/log4j-core/src/main/java/org/apache/logging/log4j/core/jmx/Server.java
+++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/jmx/Server.java
@@ -174,7 +174,7 @@ public final class Server {
                 register(mbs, mbean, mbean.getObjectName());
 
                 if (ctx instanceof AsyncLoggerContext) {
-                    final RingBufferAdmin rbmbean = AsyncLogger.createRingBufferAdmin(ctx.getName());
+                    final RingBufferAdmin rbmbean = ((AsyncLoggerContext) ctx).createRingBufferAdmin();
                     register(mbs, rbmbean, rbmbean.getObjectName());
                 }
 


[04/14] logging-log4j2 git commit: LOG4J2-493 changes to AsyncLogger because AsyncLoggerHelper is no longer static

Posted by rp...@apache.org.
LOG4J2-493 changes to AsyncLogger because AsyncLoggerHelper is no longer
static

Project: http://git-wip-us.apache.org/repos/asf/logging-log4j2/repo
Commit: http://git-wip-us.apache.org/repos/asf/logging-log4j2/commit/dc629343
Tree: http://git-wip-us.apache.org/repos/asf/logging-log4j2/tree/dc629343
Diff: http://git-wip-us.apache.org/repos/asf/logging-log4j2/diff/dc629343

Branch: refs/heads/master
Commit: dc629343b71c47c972ac5673628b32b82ae33bef
Parents: 12f90a9
Author: rpopma <rp...@apache.org>
Authored: Thu Oct 22 10:37:41 2015 +0900
Committer: rpopma <rp...@apache.org>
Committed: Thu Oct 22 10:37:41 2015 +0900

----------------------------------------------------------------------
 .../logging/log4j/core/async/AsyncLogger.java   | 21 +++++++-------------
 1 file changed, 7 insertions(+), 14 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/dc629343/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLogger.java
----------------------------------------------------------------------
diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLogger.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLogger.java
index 72d81d3..486bf69 100644
--- a/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLogger.java
+++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLogger.java
@@ -27,7 +27,6 @@ import org.apache.logging.log4j.core.LoggerContext;
 import org.apache.logging.log4j.core.config.Property;
 import org.apache.logging.log4j.core.config.ReliabilityStrategy;
 import org.apache.logging.log4j.core.impl.Log4jLogEvent;
-import org.apache.logging.log4j.core.jmx.RingBufferAdmin;
 import org.apache.logging.log4j.core.util.Clock;
 import org.apache.logging.log4j.core.util.ClockFactory;
 import org.apache.logging.log4j.core.util.DummyNanoClock;
@@ -65,6 +64,7 @@ public class AsyncLogger extends Logger {
 
     private static final Clock CLOCK = ClockFactory.getClock();
     private static volatile NanoClock nanoClock = new DummyNanoClock();
+    private AsyncLoggerHelper helper;
 
     /**
      * Constructs an {@code AsyncLogger} with the specified context, name and message factory.
@@ -72,16 +72,19 @@ public class AsyncLogger extends Logger {
      * @param context context of this logger
      * @param name name of this logger
      * @param messageFactory message factory of this logger
+     * @param helper 
      */
-    public AsyncLogger(final LoggerContext context, final String name, final MessageFactory messageFactory) {
+    public AsyncLogger(final LoggerContext context, final String name, final MessageFactory messageFactory,
+            AsyncLoggerHelper helper) {
         super(context, name, messageFactory);
+        this.helper = helper;
     }
 
     @Override
     public void logMessage(final String fqcn, final Level level, final Marker marker, final Message message,
             final Throwable thrown) {
 
-        final Disruptor<RingBufferLogEvent> temp = AsyncLoggerHelper.getDisruptor();
+        final Disruptor<RingBufferLogEvent> temp = helper.getDisruptor();
         if (temp == null) { // LOG4J2-639
             LOGGER.fatal("Ignoring log event after log4j was shut down");
         } else {
@@ -143,7 +146,7 @@ public class AsyncLogger extends Logger {
         message.getFormattedMessage(); // LOG4J2-763: ask message to freeze parameters
 
         initLogMessageInfo(info, fqcn, level, marker, message, thrown);
-        AsyncLoggerHelper.enqueueLogMessageInfo(info.translator);
+        helper.enqueueLogMessageInfo(info.translator);
     }
 
     private void initLogMessageInfo(Info info, final String fqcn, final Level level, final Marker marker,
@@ -212,16 +215,6 @@ public class AsyncLogger extends Logger {
     }
 
     /**
-     * Creates and returns a new {@code RingBufferAdmin} that instruments the ringbuffer of the {@code AsyncLogger}.
-     *
-     * @param contextName name of the global {@code AsyncLoggerContext}
-     * @return a new {@code RingBufferAdmin} that instruments the ringbuffer
-     */
-    public static RingBufferAdmin createRingBufferAdmin(final String contextName) {
-        return AsyncLoggerHelper.createRingBufferAdmin(contextName);
-    }
-
-    /**
      * Returns the {@code NanoClock} to use for creating the nanoTime timestamp of log events.
      * 
      * @return the {@code NanoClock} to use for creating the nanoTime timestamp of log events


[12/14] logging-log4j2 git commit: LOG4J2-493 RingBufferAdmin MBean can now be obtained from AsyncLoggerContext

Posted by rp...@apache.org.
LOG4J2-493 RingBufferAdmin MBean can now be obtained from
AsyncLoggerContext

Project: http://git-wip-us.apache.org/repos/asf/logging-log4j2/repo
Commit: http://git-wip-us.apache.org/repos/asf/logging-log4j2/commit/6659d55f
Tree: http://git-wip-us.apache.org/repos/asf/logging-log4j2/tree/6659d55f
Diff: http://git-wip-us.apache.org/repos/asf/logging-log4j2/diff/6659d55f

Branch: refs/heads/master
Commit: 6659d55f9d93aa2fcb4ad9f9bdec63da700771e1
Parents: 4e1fa44
Author: rpopma <rp...@apache.org>
Authored: Fri Oct 23 02:23:32 2015 +0900
Committer: rpopma <rp...@apache.org>
Committed: Fri Oct 23 02:23:32 2015 +0900

----------------------------------------------------------------------
 .../src/main/java/org/apache/logging/log4j/core/jmx/Server.java     | 1 -
 1 file changed, 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/6659d55f/log4j-core/src/main/java/org/apache/logging/log4j/core/jmx/Server.java
----------------------------------------------------------------------
diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/jmx/Server.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/jmx/Server.java
index b3f4614..c4f596d 100644
--- a/log4j-core/src/main/java/org/apache/logging/log4j/core/jmx/Server.java
+++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/jmx/Server.java
@@ -34,7 +34,6 @@ import org.apache.logging.log4j.LogManager;
 import org.apache.logging.log4j.core.Appender;
 import org.apache.logging.log4j.core.LoggerContext;
 import org.apache.logging.log4j.core.appender.AsyncAppender;
-import org.apache.logging.log4j.core.async.AsyncLogger;
 import org.apache.logging.log4j.core.async.AsyncLoggerConfig;
 import org.apache.logging.log4j.core.async.AsyncLoggerContext;
 import org.apache.logging.log4j.core.async.DaemonThreadFactory;


[07/14] logging-log4j2 git commit: fix test to work correctly on machines where locale is en_US but date symbols are Japanese

Posted by rp...@apache.org.
fix test to work correctly on machines where locale is en_US but date
symbols are Japanese

Project: http://git-wip-us.apache.org/repos/asf/logging-log4j2/repo
Commit: http://git-wip-us.apache.org/repos/asf/logging-log4j2/commit/6e45177d
Tree: http://git-wip-us.apache.org/repos/asf/logging-log4j2/tree/6e45177d
Diff: http://git-wip-us.apache.org/repos/asf/logging-log4j2/diff/6e45177d

Branch: refs/heads/master
Commit: 6e45177dd8ab5509a28d3f45312405db5edf2dd0
Parents: 59cc8e5
Author: rpopma <rp...@apache.org>
Authored: Fri Oct 23 01:51:33 2015 +0900
Committer: rpopma <rp...@apache.org>
Committed: Fri Oct 23 01:51:33 2015 +0900

----------------------------------------------------------------------
 .../log4j/core/util/datetime/FixedDateFormatTest.java  | 13 +++++++------
 1 file changed, 7 insertions(+), 6 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/6e45177d/log4j-core/src/test/java/org/apache/logging/log4j/core/util/datetime/FixedDateFormatTest.java
----------------------------------------------------------------------
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/util/datetime/FixedDateFormatTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/util/datetime/FixedDateFormatTest.java
index dc222e7..8bfc6af 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/util/datetime/FixedDateFormatTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/util/datetime/FixedDateFormatTest.java
@@ -19,6 +19,7 @@ package org.apache.logging.log4j.core.util.datetime;
 
 import java.text.SimpleDateFormat;
 import java.util.Date;
+import java.util.Locale;
 import java.util.concurrent.TimeUnit;
 
 import org.apache.logging.log4j.core.util.datetime.FixedDateFormat.FixedFormat;
@@ -68,7 +69,7 @@ public class FixedDateFormatTest {
         assertEquals("yyyyMMdd", FixedFormat.COMPACT.getFastDateFormat().getPattern());
         assertEquals("yyyy-MM-dd ", FixedFormat.DEFAULT.getFastDateFormat().getPattern());
     }
-    
+
     @Test
     public void testCreateIfSupported_nonNullIfNameMatches() {
         for (final FixedDateFormat.FixedFormat format : FixedDateFormat.FixedFormat.values()) {
@@ -121,7 +122,7 @@ public class FixedDateFormatTest {
         assertNull("timezone", FixedDateFormat.createIfSupported(options));
     }
 
-    @Test(expected=NullPointerException.class)
+    @Test(expected = NullPointerException.class)
     public void testConstructorDisallowsNull() {
         new FixedDateFormat(null);
     }
@@ -138,7 +139,7 @@ public class FixedDateFormatTest {
         final long start = now - TimeUnit.HOURS.toMillis(25);
         final long end = now + TimeUnit.HOURS.toMillis(25);
         for (final FixedFormat format : FixedFormat.values()) {
-            final SimpleDateFormat simpleDF = new SimpleDateFormat(format.getPattern());
+            final SimpleDateFormat simpleDF = new SimpleDateFormat(format.getPattern(), Locale.getDefault());
             final FixedDateFormat customTF = new FixedDateFormat(format);
             for (long time = start; time < end; time += 12345) {
                 final String actual = customTF.format(time);
@@ -154,7 +155,7 @@ public class FixedDateFormatTest {
         final long start = now - TimeUnit.HOURS.toMillis(25);
         final long end = now + TimeUnit.HOURS.toMillis(25);
         for (final FixedFormat format : FixedFormat.values()) {
-            final SimpleDateFormat simpleDF = new SimpleDateFormat(format.getPattern());
+            final SimpleDateFormat simpleDF = new SimpleDateFormat(format.getPattern(), Locale.getDefault());
             final FixedDateFormat customTF = new FixedDateFormat(format);
             for (long time = end; time > start; time -= 12345) {
                 final String actual = customTF.format(time);
@@ -171,7 +172,7 @@ public class FixedDateFormatTest {
         final long end = now + TimeUnit.HOURS.toMillis(25);
         final char[] buffer = new char[128];
         for (final FixedFormat format : FixedFormat.values()) {
-            final SimpleDateFormat simpleDF = new SimpleDateFormat(format.getPattern());
+            final SimpleDateFormat simpleDF = new SimpleDateFormat(format.getPattern(), Locale.getDefault());
             final FixedDateFormat customTF = new FixedDateFormat(format);
             for (long time = start; time < end; time += 12345) {
                 final int length = customTF.format(time, buffer, 23);
@@ -189,7 +190,7 @@ public class FixedDateFormatTest {
         final long end = now + TimeUnit.HOURS.toMillis(25);
         final char[] buffer = new char[128];
         for (final FixedFormat format : FixedFormat.values()) {
-            final SimpleDateFormat simpleDF = new SimpleDateFormat(format.getPattern());
+            final SimpleDateFormat simpleDF = new SimpleDateFormat(format.getPattern(), Locale.getDefault());
             final FixedDateFormat customTF = new FixedDateFormat(format);
             for (long time = end; time > start; time -= 12345) {
                 final int length = customTF.format(time, buffer, 23);


[14/14] logging-log4j2 git commit: LOG4J2-493 test fixes

Posted by rp...@apache.org.
LOG4J2-493 test fixes

Project: http://git-wip-us.apache.org/repos/asf/logging-log4j2/repo
Commit: http://git-wip-us.apache.org/repos/asf/logging-log4j2/commit/7ffd4cfe
Tree: http://git-wip-us.apache.org/repos/asf/logging-log4j2/tree/7ffd4cfe
Diff: http://git-wip-us.apache.org/repos/asf/logging-log4j2/diff/7ffd4cfe

Branch: refs/heads/master
Commit: 7ffd4cfe1fec0316a5cd79167f2250cba6752984
Parents: 4b0b01d
Author: rpopma <rp...@apache.org>
Authored: Fri Oct 23 02:39:24 2015 +0900
Committer: rpopma <rp...@apache.org>
Committed: Fri Oct 23 02:39:24 2015 +0900

----------------------------------------------------------------------
 ...ncLoggerContextSelectorInitialStateTest.java | 30 ++++++++++++++++++++
 .../async/AsyncLoggerContextSelectorTest.java   | 18 +++++-------
 2 files changed, 37 insertions(+), 11 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/7ffd4cfe/log4j-core/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerContextSelectorInitialStateTest.java
----------------------------------------------------------------------
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerContextSelectorInitialStateTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerContextSelectorInitialStateTest.java
new file mode 100644
index 0000000..2d547ed
--- /dev/null
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerContextSelectorInitialStateTest.java
@@ -0,0 +1,30 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.logging.log4j.core.async;
+
+import org.junit.Test;
+
+import static org.junit.Assert.*;
+
+public class AsyncLoggerContextSelectorInitialStateTest {    
+
+    @Test
+    public void testLoggerContextsListInitiallyEmpty() {
+        final AsyncLoggerContextSelector selector = new AsyncLoggerContextSelector();
+        assertTrue(selector.getLoggerContexts().isEmpty());
+    }
+}

http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/7ffd4cfe/log4j-core/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerContextSelectorTest.java
----------------------------------------------------------------------
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerContextSelectorTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerContextSelectorTest.java
index 23c4cdd..324aa84 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerContextSelectorTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerContextSelectorTest.java
@@ -24,11 +24,13 @@ import org.junit.Test;
 import static org.junit.Assert.*;
 
 public class AsyncLoggerContextSelectorTest {
+    
+    private static final String FQCN = AsyncLoggerContextSelectorTest.class.getName();
 
     @Test
     public void testContextReturnsAsyncLoggerContext() {
         final AsyncLoggerContextSelector selector = new AsyncLoggerContextSelector();
-        final LoggerContext context = selector.getContext(null, null, false);
+        final LoggerContext context = selector.getContext(FQCN, null, false);
 
         assertTrue(context instanceof AsyncLoggerContext);
     }
@@ -36,21 +38,15 @@ public class AsyncLoggerContextSelectorTest {
     @Test
     public void testContext2ReturnsAsyncLoggerContext() {
         final AsyncLoggerContextSelector selector = new AsyncLoggerContextSelector();
-        final LoggerContext context = selector.getContext(null, null, false, null);
+        final LoggerContext context = selector.getContext(FQCN, null, false, null);
 
         assertTrue(context instanceof AsyncLoggerContext);
     }
 
     @Test
-    public void testLoggerContextsListInitiallyEmpty() {
-        final AsyncLoggerContextSelector selector = new AsyncLoggerContextSelector();
-        assertTrue(selector.getLoggerContexts().isEmpty());
-    }
-
-    @Test
     public void testLoggerContextsReturnsAsyncLoggerContext() {
         final AsyncLoggerContextSelector selector = new AsyncLoggerContextSelector();
-        selector.getContext(null, null, false);
+        selector.getContext(FQCN, null, false);
 
         final List<LoggerContext> list = selector.getLoggerContexts();
         assertEquals(1, list.size());
@@ -60,9 +56,9 @@ public class AsyncLoggerContextSelectorTest {
     @Test
     public void testContextNameIsAsyncLoggerContextWithClassHashCode() {
         final AsyncLoggerContextSelector selector = new AsyncLoggerContextSelector();
-        final LoggerContext context = selector.getContext(null, null, false);
+        final LoggerContext context = selector.getContext(FQCN, null, false);
         final int hash = getClass().getClassLoader().hashCode();
-        final String expectedContextName = "AsyncLoggerContext@" + Integer.toHexString(hash);
+        final String expectedContextName = "AsyncContext@" + Integer.toHexString(hash);
         assertEquals(expectedContextName, context.getName());
     }
 


[11/14] logging-log4j2 git commit: LOG4J2-493 AsyncLoggerHelper constructor now takes context name; formatted code.

Posted by rp...@apache.org.
LOG4J2-493 AsyncLoggerHelper constructor now takes context name;
formatted code.

Project: http://git-wip-us.apache.org/repos/asf/logging-log4j2/repo
Commit: http://git-wip-us.apache.org/repos/asf/logging-log4j2/commit/4e1fa44a
Tree: http://git-wip-us.apache.org/repos/asf/logging-log4j2/tree/4e1fa44a
Diff: http://git-wip-us.apache.org/repos/asf/logging-log4j2/diff/4e1fa44a

Branch: refs/heads/master
Commit: 4e1fa44af4ffbb088cceed9092a7866ae97e2384
Parents: 3705a75
Author: rpopma <rp...@apache.org>
Authored: Fri Oct 23 02:22:34 2015 +0900
Committer: rpopma <rp...@apache.org>
Committed: Fri Oct 23 02:22:34 2015 +0900

----------------------------------------------------------------------
 .../log4j/core/async/AsyncLoggerContext.java    | 27 ++++++++++----------
 1 file changed, 14 insertions(+), 13 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/4e1fa44a/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLoggerContext.java
----------------------------------------------------------------------
diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLoggerContext.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLoggerContext.java
index f9e707b..4efd7cc 100644
--- a/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLoggerContext.java
+++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLoggerContext.java
@@ -30,38 +30,37 @@ import org.apache.logging.log4j.message.MessageFactory;
 public class AsyncLoggerContext extends LoggerContext {
 
     private static final long serialVersionUID = 1L;
-    
+
     private final AsyncLoggerHelper helper;
 
     public AsyncLoggerContext(final String name) {
         super(name);
-        helper = new AsyncLoggerHelper();
+        helper = new AsyncLoggerHelper(name);
     }
 
     public AsyncLoggerContext(final String name, final Object externalContext) {
         super(name, externalContext);
-        helper = new AsyncLoggerHelper();
+        helper = new AsyncLoggerHelper(name);
     }
 
-    public AsyncLoggerContext(final String name, final Object externalContext,
-            final URI configLocn) {
+    public AsyncLoggerContext(final String name, final Object externalContext, final URI configLocn) {
         super(name, externalContext, configLocn);
-        helper = new AsyncLoggerHelper();
+        helper = new AsyncLoggerHelper(name);
     }
 
-    public AsyncLoggerContext(final String name, final Object externalContext,
-            final String configLocn) {
+    public AsyncLoggerContext(final String name, final Object externalContext, final String configLocn) {
         super(name, externalContext, configLocn);
-        helper = new AsyncLoggerHelper();
+        helper = new AsyncLoggerHelper(name);
     }
 
     @Override
-    protected Logger newInstance(final LoggerContext ctx, final String name,
-            final MessageFactory messageFactory) {
+    protected Logger newInstance(final LoggerContext ctx, final String name, final MessageFactory messageFactory) {
         return new AsyncLogger(ctx, name, messageFactory, helper);
     }
 
-    /* (non-Javadoc)
+    /*
+     * (non-Javadoc)
+     * 
      * @see org.apache.logging.log4j.core.LoggerContext#start()
      */
     @Override
@@ -70,7 +69,9 @@ public class AsyncLoggerContext extends LoggerContext {
         super.start();
     }
 
-    /* (non-Javadoc)
+    /*
+     * (non-Javadoc)
+     * 
      * @see org.apache.logging.log4j.core.LoggerContext#start(org.apache.logging.log4j.core.config.Configuration)
      */
     @Override


[06/14] logging-log4j2 git commit: added benchmark

Posted by rp...@apache.org.
added benchmark

Project: http://git-wip-us.apache.org/repos/asf/logging-log4j2/repo
Commit: http://git-wip-us.apache.org/repos/asf/logging-log4j2/commit/59cc8e58
Tree: http://git-wip-us.apache.org/repos/asf/logging-log4j2/tree/59cc8e58
Diff: http://git-wip-us.apache.org/repos/asf/logging-log4j2/diff/59cc8e58

Branch: refs/heads/master
Commit: 59cc8e58fc91884fedb4795abe85eca0832b49f5
Parents: 3195cda
Author: rpopma <rp...@apache.org>
Authored: Fri Oct 23 00:33:17 2015 +0900
Committer: rpopma <rp...@apache.org>
Committed: Fri Oct 23 00:33:17 2015 +0900

----------------------------------------------------------------------
 ...ThreadLocalVsConcurrentHashMapBenchmark.java | 94 ++++++++++++++++++++
 1 file changed, 94 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/59cc8e58/log4j-perf/src/main/java/org/apache/logging/log4j/perf/jmh/ThreadLocalVsConcurrentHashMapBenchmark.java
----------------------------------------------------------------------
diff --git a/log4j-perf/src/main/java/org/apache/logging/log4j/perf/jmh/ThreadLocalVsConcurrentHashMapBenchmark.java b/log4j-perf/src/main/java/org/apache/logging/log4j/perf/jmh/ThreadLocalVsConcurrentHashMapBenchmark.java
new file mode 100644
index 0000000..7ba0ca4
--- /dev/null
+++ b/log4j-perf/src/main/java/org/apache/logging/log4j/perf/jmh/ThreadLocalVsConcurrentHashMapBenchmark.java
@@ -0,0 +1,94 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.logging.log4j.perf.jmh;
+
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.openjdk.jmh.annotations.Benchmark;
+import org.openjdk.jmh.annotations.Scope;
+import org.openjdk.jmh.annotations.State;
+
+/**
+ * Compares performance of ThreadLocal, vs ConcurrentHashMap&lt;Thread, Object&gt;.
+ */
+// ============================== HOW TO RUN THIS TEST: ====================================
+// (Quick build: mvn -DskipTests=true clean package -pl log4j-perf -am )
+//
+// single thread:
+// java -jar log4j-perf/target/benchmarks.jar ".*ThreadLocalVsConcurrentHashMap.*" -f 1 -wi 10 -i 20 -tu ns -bm sample
+//
+// four threads:
+// java -jar log4j-perf/target/benchmarks.jar ".*ThreadLocalVsConcurrentHashMap.*" -f 1 -wi 10 -i 20 -tu ns -bm sample
+// -t 4
+//
+// Usage help:
+// java -jar log4j-perf/target/benchmarks.jar -help
+//
+@State(Scope.Benchmark)
+public class ThreadLocalVsConcurrentHashMapBenchmark {
+
+    private static final String VALUE = "value";
+    private static ConcurrentHashMap<Thread, StringBuilder> map = new ConcurrentHashMap<Thread, StringBuilder>();
+    private static ThreadLocal<StringBuilder> threadLocal = new ThreadLocal<>();
+
+    @Benchmark
+    public String newInstance() {
+        StringBuilder sb = getNew();
+        sb.append(VALUE);
+        return sb.toString();
+    }
+
+    @Benchmark
+    public String threadLocal() {
+        StringBuilder sb = getThreadLocal();
+        sb.append(VALUE);
+        return sb.toString();
+    }
+
+    @Benchmark
+    public String concurrentHashMap() {
+        StringBuilder sb = getConcurrentMap();
+        sb.append(VALUE);
+        return sb.toString();
+    }
+
+    private StringBuilder getNew() {
+        final StringBuilder buf = new StringBuilder();
+        return buf;
+    }
+
+    private StringBuilder getThreadLocal() {
+        StringBuilder buf = threadLocal.get();
+        if (buf == null) {
+            buf = new StringBuilder();
+            threadLocal.set(buf);
+        }
+        buf.setLength(0);
+        return buf;
+    }
+
+    private StringBuilder getConcurrentMap() {
+        StringBuilder buf = map.get(Thread.currentThread());
+        if (buf == null) {
+            buf = new StringBuilder();
+            map.put(Thread.currentThread(), buf);
+        }
+        buf.setLength(0);
+        return buf;
+    }
+}
\ No newline at end of file


[09/14] logging-log4j2 git commit: LOG4J2-493 factored out context creation to separate method to facilitate subclassing, formatted code.

Posted by rp...@apache.org.
LOG4J2-493 factored out context creation to separate method to
facilitate subclassing, formatted code.

Project: http://git-wip-us.apache.org/repos/asf/logging-log4j2/repo
Commit: http://git-wip-us.apache.org/repos/asf/logging-log4j2/commit/7800b8f0
Tree: http://git-wip-us.apache.org/repos/asf/logging-log4j2/tree/7800b8f0
Diff: http://git-wip-us.apache.org/repos/asf/logging-log4j2/diff/7800b8f0

Branch: refs/heads/master
Commit: 7800b8f0416c6d9370de3eb7ab5da6e1ffdce36e
Parents: 25fe68d
Author: rpopma <rp...@apache.org>
Authored: Fri Oct 23 02:18:50 2015 +0900
Committer: rpopma <rp...@apache.org>
Committed: Fri Oct 23 02:18:50 2015 +0900

----------------------------------------------------------------------
 .../selector/ClassLoaderContextSelector.java    | 44 +++++++++++---------
 1 file changed, 25 insertions(+), 19 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/7800b8f0/log4j-core/src/main/java/org/apache/logging/log4j/core/selector/ClassLoaderContextSelector.java
----------------------------------------------------------------------
diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/selector/ClassLoaderContextSelector.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/selector/ClassLoaderContextSelector.java
index f7fa5d4..6aa87b0 100644
--- a/log4j-core/src/main/java/org/apache/logging/log4j/core/selector/ClassLoaderContextSelector.java
+++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/selector/ClassLoaderContextSelector.java
@@ -33,11 +33,11 @@ import org.apache.logging.log4j.status.StatusLogger;
 import org.apache.logging.log4j.util.ReflectionUtil;
 
 /**
- * This ContextSelector chooses a LoggerContext based upon the ClassLoader of the caller. This allows Loggers
- * assigned to static variables to be released along with the classes that own then. Other ContextSelectors
- * will generally cause Loggers associated with classes loaded from different ClassLoaders to be co-mingled.
- * This is a problem if, for example, a web application is undeployed as some of the Loggers being released may be
- * associated with a Class in a parent ClassLoader, which will generally have negative consequences.
+ * This ContextSelector chooses a LoggerContext based upon the ClassLoader of the caller. This allows Loggers assigned
+ * to static variables to be released along with the classes that own then. Other ContextSelectors will generally cause
+ * Loggers associated with classes loaded from different ClassLoaders to be co-mingled. This is a problem if, for
+ * example, a web application is undeployed as some of the Loggers being released may be associated with a Class in a
+ * parent ClassLoader, which will generally have negative consequences.
  *
  * The main downside to this ContextSelector is that Configuration is more challenging.
  *
@@ -45,12 +45,12 @@ import org.apache.logging.log4j.util.ReflectionUtil;
  */
 public class ClassLoaderContextSelector implements ContextSelector {
 
-    private static final AtomicReference<LoggerContext> CONTEXT = new AtomicReference<>();
+    private static final AtomicReference<LoggerContext> DEFAULT_CONTEXT = new AtomicReference<>();
 
     protected static final StatusLogger LOGGER = StatusLogger.getLogger();
 
     protected static final ConcurrentMap<String, AtomicReference<WeakReference<LoggerContext>>> CONTEXT_MAP =
-        new ConcurrentHashMap<>();
+            new ConcurrentHashMap<>();
 
     @Override
     public LoggerContext getContext(final String fqcn, final ClassLoader loader, final boolean currentContext) {
@@ -59,7 +59,7 @@ public class ClassLoaderContextSelector implements ContextSelector {
 
     @Override
     public LoggerContext getContext(final String fqcn, final ClassLoader loader, final boolean currentContext,
-                                    final URI configLocation) {
+            final URI configLocation) {
         if (currentContext) {
             final LoggerContext ctx = ContextAnchor.THREAD_CONTEXT.get();
             if (ctx != null) {
@@ -142,9 +142,8 @@ public class ClassLoaderContextSelector implements ContextSelector {
                     } */
                 }
             }
-            LoggerContext ctx = new LoggerContext(name, null, configLocation);
-            final AtomicReference<WeakReference<LoggerContext>> r =
-                new AtomicReference<>();
+            LoggerContext ctx = createContext(name, configLocation);
+            final AtomicReference<WeakReference<LoggerContext>> r = new AtomicReference<>();
             r.set(new WeakReference<>(ctx));
             CONTEXT_MAP.putIfAbsent(name, r);
             ctx = CONTEXT_MAP.get(name).get().get();
@@ -156,29 +155,36 @@ public class ClassLoaderContextSelector implements ContextSelector {
             if (ctx.getConfigLocation() == null && configLocation != null) {
                 LOGGER.debug("Setting configuration to {}", configLocation);
                 ctx.setConfigLocation(configLocation);
-            } else if (ctx.getConfigLocation() != null && configLocation != null &&
-                !ctx.getConfigLocation().equals(configLocation)) {
+            } else if (ctx.getConfigLocation() != null && configLocation != null
+                    && !ctx.getConfigLocation().equals(configLocation)) {
                 LOGGER.warn("locateContext called with URI {}. Existing LoggerContext has URI {}", configLocation,
-                    ctx.getConfigLocation());
+                        ctx.getConfigLocation());
             }
             return ctx;
         }
-        ctx = new LoggerContext(name, null, configLocation);
+        ctx = createContext(name, configLocation);
         ref.compareAndSet(weakRef, new WeakReference<>(ctx));
         return ctx;
     }
 
-    private String toContextMapKey(final ClassLoader loader) {
+    protected LoggerContext createContext(final String name, final URI configLocation) {
+        return new LoggerContext(name, null, configLocation);
+    }
+
+    protected String toContextMapKey(final ClassLoader loader) {
         return Integer.toHexString(System.identityHashCode(loader));
     }
 
     protected LoggerContext getDefault() {
-        final LoggerContext ctx = CONTEXT.get();
+        final LoggerContext ctx = DEFAULT_CONTEXT.get();
         if (ctx != null) {
             return ctx;
         }
-        CONTEXT.compareAndSet(null, new LoggerContext("Default"));
-        return CONTEXT.get();
+        DEFAULT_CONTEXT.compareAndSet(null, createContext(defaultContextName(), null));
+        return DEFAULT_CONTEXT.get();
     }
 
+    protected String defaultContextName() {
+        return "Default";
+    }
 }