logging-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From mattsic...@apache.org
Subject svn commit: r1611967 - in /logging/log4j/log4j2/trunk: log4j-web/src/main/java/org/apache/logging/log4j/web/ log4j-web/src/test/java/org/apache/logging/log4j/web/ src/site/xdoc/manual/
Date Sat, 19 Jul 2014 21:18:53 GMT
Author: mattsicker
Date: Sat Jul 19 21:18:53 2014
New Revision: 1611967

URL: http://svn.apache.org/r1611967
Log:
Add Runnable wrapper method for use with Async Servlets.

  - Updated documentation.
  - Moved implementation of getLog4jWebInitializer into WebLoggerContextUtils.
  - Added WebLoggerContextUtils which is similar to Spring's WebApplicationContextUtils class.
  - Added test servlet for later integration testing (also used for example documentation).

Added:
    logging/log4j/log4j2/trunk/log4j-web/src/main/java/org/apache/logging/log4j/web/WebLoggerContextUtils.java
    logging/log4j/log4j2/trunk/log4j-web/src/test/java/org/apache/logging/log4j/web/TestAsyncServlet.java
Modified:
    logging/log4j/log4j2/trunk/log4j-web/src/main/java/org/apache/logging/log4j/web/Log4jWebInitializerImpl.java
    logging/log4j/log4j2/trunk/src/site/xdoc/manual/webapp.xml

Modified: logging/log4j/log4j2/trunk/log4j-web/src/main/java/org/apache/logging/log4j/web/Log4jWebInitializerImpl.java
URL: http://svn.apache.org/viewvc/logging/log4j/log4j2/trunk/log4j-web/src/main/java/org/apache/logging/log4j/web/Log4jWebInitializerImpl.java?rev=1611967&r1=1611966&r2=1611967&view=diff
==============================================================================
--- logging/log4j/log4j2/trunk/log4j-web/src/main/java/org/apache/logging/log4j/web/Log4jWebInitializerImpl.java
(original)
+++ logging/log4j/log4j2/trunk/log4j-web/src/main/java/org/apache/logging/log4j/web/Log4jWebInitializerImpl.java
Sat Jul 19 21:18:53 2014
@@ -16,13 +16,10 @@
  */
 package org.apache.logging.log4j.web;
 
-import java.net.MalformedURLException;
 import java.net.URI;
 import java.net.URL;
 import java.util.Map;
-import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
-
 import javax.servlet.ServletContext;
 
 import org.apache.logging.log4j.LogManager;
@@ -45,7 +42,6 @@ import org.apache.logging.log4j.spi.Logg
  * This class initializes and deinitializes Log4j no matter how the initialization occurs.
  */
 final class Log4jWebInitializerImpl extends AbstractLifeCycle implements Log4jWebLifeCycle
{
-    private static final Object MUTEX = new Object();
 
     static {
         if (Loader.isClassAvailable("org.apache.logging.log4j.core.web.JNDIContextFilter"))
{
@@ -68,6 +64,20 @@ final class Log4jWebInitializerImpl exte
         this.map.put("hostName", NetUtils.getLocalHostname());
     }
 
+    /**
+     * Initializes the Log4jWebLifeCycle attribute of a ServletContext. Those who wish to
obtain this object should
+     * use the {@link org.apache.logging.log4j.web.WebLoggerContextUtils#getWebLifeCycle(javax.servlet.ServletContext)}
+     * method instead.
+     *
+     * @param servletContext the ServletContext to initialize
+     * @return a new Log4jWebLifeCycle
+     */
+    protected static Log4jWebInitializerImpl initialize(final ServletContext servletContext)
{
+        final Log4jWebInitializerImpl initializer = new Log4jWebInitializerImpl(servletContext);
+        servletContext.setAttribute(SUPPORT_ATTRIBUTE, initializer);
+        return initializer;
+    }
+
     @Override
     public synchronized void start() {
         if (this.isStopped() || this.isStopping()) {
@@ -248,13 +258,6 @@ final class Log4jWebInitializerImpl exte
      * @return the initializer, never {@code null}.
      */
     static Log4jWebLifeCycle getLog4jWebInitializer(final ServletContext servletContext)
{
-        synchronized (MUTEX) {
-            Log4jWebLifeCycle initializer = (Log4jWebLifeCycle) servletContext.getAttribute(SUPPORT_ATTRIBUTE);
-            if (initializer == null) {
-                initializer = new Log4jWebInitializerImpl(servletContext);
-                servletContext.setAttribute(SUPPORT_ATTRIBUTE, initializer);
-            }
-            return initializer;
-        }
+        return WebLoggerContextUtils.getWebLifeCycle(servletContext);
     }
 }

Added: logging/log4j/log4j2/trunk/log4j-web/src/main/java/org/apache/logging/log4j/web/WebLoggerContextUtils.java
URL: http://svn.apache.org/viewvc/logging/log4j/log4j2/trunk/log4j-web/src/main/java/org/apache/logging/log4j/web/WebLoggerContextUtils.java?rev=1611967&view=auto
==============================================================================
--- logging/log4j/log4j2/trunk/log4j-web/src/main/java/org/apache/logging/log4j/web/WebLoggerContextUtils.java
(added)
+++ logging/log4j/log4j2/trunk/log4j-web/src/main/java/org/apache/logging/log4j/web/WebLoggerContextUtils.java
Sat Jul 19 21:18:53 2014
@@ -0,0 +1,106 @@
+/*
+ * 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.web;
+
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
+import javax.servlet.ServletContext;
+
+import org.apache.logging.log4j.core.LoggerContext;
+
+/**
+ * Convenience methods for retrieving the {@link org.apache.logging.log4j.core.LoggerContext}
associated with a
+ * particular ServletContext. These methods are most particularly useful for asynchronous
servlets where the
+ * <abbr title="Thread Context ClassLoader">TCCL</abbr> is potentially different
from the TCCL used by the
+ * Servlet container that bootstrapped Log4j.
+ */
+public final class WebLoggerContextUtils {
+    private WebLoggerContextUtils() {
+    }
+
+    private static final Lock WEB_SUPPORT_LOOKUP = new ReentrantLock();
+
+    /**
+     * Finds the main {@link org.apache.logging.log4j.core.LoggerContext} configured for
the given ServletContext.
+     *
+     * @param servletContext the ServletContext to locate a LoggerContext for
+     * @return the LoggerContext for the given ServletContext
+     * @throws java.lang.IllegalStateException if no LoggerContext could be found on the
given ServletContext
+     */
+    public static LoggerContext getWebLoggerContext(final ServletContext servletContext)
{
+        return (LoggerContext) servletContext.getAttribute(Log4jWebSupport.CONTEXT_ATTRIBUTE);
+    }
+
+    /**
+     * Finds the main {@link org.apache.logging.log4j.core.LoggerContext} configured for
the given ServletContext.
+     *
+     * @param servletContext the ServletContext to locate a LoggerContext for
+     * @return the LoggerContext for the given ServletContext or {@code null} if none was
set
+     */
+    public static LoggerContext getRequiredWebLoggerContext(final ServletContext servletContext)
{
+        final LoggerContext loggerContext = getWebLoggerContext(servletContext);
+        if (loggerContext == null) {
+            throw new IllegalStateException(
+                "No LoggerContext found in ServletContext attribute " + Log4jWebSupport.CONTEXT_ATTRIBUTE);
+        }
+        return loggerContext;
+    }
+
+    /**
+     * Finds or initializes the {@link org.apache.logging.log4j.web.Log4jWebLifeCycle} singleton
for the given
+     * ServletContext.
+     *
+     * @param servletContext the ServletContext to get the Log4jWebLifeCycle for
+     * @return the Log4jWebLifeCycle for the given ServletContext
+     */
+    public static Log4jWebLifeCycle getWebLifeCycle(final ServletContext servletContext)
{
+        WEB_SUPPORT_LOOKUP.lock();
+        try {
+            Log4jWebLifeCycle webLifeCycle = (Log4jWebLifeCycle) servletContext.getAttribute(
+                Log4jWebSupport.SUPPORT_ATTRIBUTE);
+            if (webLifeCycle == null) {
+                webLifeCycle = Log4jWebInitializerImpl.initialize(servletContext);
+            }
+            return webLifeCycle;
+        } finally {
+            WEB_SUPPORT_LOOKUP.unlock();
+        }
+    }
+
+    /**
+     * Wraps a Runnable instance by setting its thread context {@link org.apache.logging.log4j.core.LoggerContext}
+     * before execution and clearing it after execution.
+     *
+     * @param servletContext the ServletContext to locate a LoggerContext for
+     * @param runnable       the Runnable to wrap execution for
+     * @return a wrapped Runnable
+     */
+    public static Runnable wrapExecutionContext(final ServletContext servletContext, final
Runnable runnable) {
+        return new Runnable() {
+            @Override
+            public void run() {
+                final Log4jWebSupport webSupport = getWebLifeCycle(servletContext);
+                webSupport.setLoggerContext();
+                try {
+                    runnable.run();
+                } finally {
+                    webSupport.clearLoggerContext();
+                }
+            }
+        };
+    }
+}

Added: logging/log4j/log4j2/trunk/log4j-web/src/test/java/org/apache/logging/log4j/web/TestAsyncServlet.java
URL: http://svn.apache.org/viewvc/logging/log4j/log4j2/trunk/log4j-web/src/test/java/org/apache/logging/log4j/web/TestAsyncServlet.java?rev=1611967&view=auto
==============================================================================
--- logging/log4j/log4j2/trunk/log4j-web/src/test/java/org/apache/logging/log4j/web/TestAsyncServlet.java
(added)
+++ logging/log4j/log4j2/trunk/log4j-web/src/test/java/org/apache/logging/log4j/web/TestAsyncServlet.java
Sat Jul 19 21:18:53 2014
@@ -0,0 +1,57 @@
+/*
+ * 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.web;
+
+import java.io.IOException;
+import javax.servlet.AsyncContext;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
+// TODO: write an integration test that deploys this Servlet 3.0 class to Tomcat and Jetty
+public class TestAsyncServlet extends HttpServlet {
+    @Override
+    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException {
+        final AsyncContext asyncContext = req.startAsync();
+        asyncContext.start(WebLoggerContextUtils.wrapExecutionContext(this.getServletContext(),
new Runnable() {
+            @Override
+            public void run() {
+                final Logger logger = LogManager.getLogger(TestAsyncServlet.class);
+                logger.info("Hello, servlet!");
+            }
+        }));
+    }
+
+    @Override
+    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException {
+        final AsyncContext asyncContext = req.startAsync();
+        asyncContext.start(new Runnable() {
+            @Override
+            public void run() {
+                final Log4jWebSupport webSupport =
+                    WebLoggerContextUtils.getWebLifeCycle(TestAsyncServlet.this.getServletContext());
+                webSupport.setLoggerContext();
+                // do stuff
+                webSupport.clearLoggerContext();
+            }
+        });
+    }
+}

Modified: logging/log4j/log4j2/trunk/src/site/xdoc/manual/webapp.xml
URL: http://svn.apache.org/viewvc/logging/log4j/log4j2/trunk/src/site/xdoc/manual/webapp.xml?rev=1611967&r1=1611966&r2=1611967&view=diff
==============================================================================
--- logging/log4j/log4j2/trunk/src/site/xdoc/manual/webapp.xml (original)
+++ logging/log4j/log4j2/trunk/src/site/xdoc/manual/webapp.xml Sat Jul 19 21:18:53 2014
@@ -22,6 +22,7 @@
   <properties>
     <title>Log4j 2 Web Applications</title>
     <author email="nickwilliams@apache.org">Nick Williams</author>
+    <author email="mattsicker@apache.org">Matt Sicker</author>
   </properties>
 
   <body>
@@ -285,63 +286,110 @@
         </p>
         <p>
           Thankfully, Log4j provides a simple mechanism for binding the <code>LoggerContext</code>
to asynchronous
-          threads in these special circumstances. The key is to obtain a
-          <a href="../log4j-core/apidocs/org/apache/logging/log4j/web/Log4jWebSupport.html"
-              >Log4jWebSupport</a> instance from the <code>ServletContext</code>
attributes, call its
-          <code>setLoggerContext</code> method as the very first line of code
in your asynchronous thread, and call
-          its <code>clearLoggerContext</code> method as the very last line of
code in your asynchronous thread. The
-          following code demonstrates this. It uses the container thread pool to execute
asynchronous request
-          processing, passing an anonymous inner <code>Runnable</code> to the
<code>start</code> method.
+          threads in these special circumstances. The simplest way to do this is to wrap
the <code>Runnable</code>
+          instance that is passed to the <code>AsyncContext.start()</code> method.
         </p>
-        <pre class="prettyprint linenums"><![CDATA[public class AsyncServlet extends
HttpServlet
-{
+        <pre class="prettyprint linenums"><![CDATA[
+import java.io.IOException;
+import javax.servlet.AsyncContext;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+import org.apache.logging.log4j.web.WebLoggerContextUtils;
+
+public class TestAsyncServlet extends HttpServlet {
     @Override
-    protected void doGet(HttpServletRequest request, HttpServletResponse response)
-            throws ServletException, IOException
-    {
-        final AsyncContext context = request.startAsync(request, response);
-        context.setTimeout(timeout);
-        context.start(new Runnable() {
+    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException {
+        final AsyncContext asyncContext = req.startAsync();
+        asyncContext.start(WebLoggerContextUtils.wrapExecutionContext(getServletContext(),
new Runnable() {
             @Override
             public void run() {
-                Log4jWebSupport support = (Log4jWebSupport)this.getServletContext()
-                        .getAttribute(Log4jWebSupport.SUPPORT_ATTRIBUTE);
-                support.setLoggerContext();
+                final Logger logger = LogManager.getLogger(TestAsyncServlet.class);
+                logger.info("Hello, servlet!");
+            }
+        }));
+    }
+}
+        ]]></pre>
+        <p>
+          This can be slightly more convenient when using Java 1.8 and lambda functions as
demonstrated below.
+        </p>
+        <pre class="prettyprint linenums"><![CDATA[
+import java.io.IOException;
+import javax.servlet.AsyncContext;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+import org.apache.logging.log4j.web.WebLoggerContextUtils;
 
+public class TestAsyncServlet extends HttpServlet {
+    @Override
+    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException {
+        final AsyncContext asyncContext = req.startAsync();
+        asyncContext.start(WebLoggerContextUtils.wrapExecutionContext(this.getServletContext(),
() -> {
+            final Logger logger = LogManager.getLogger(TestAsyncServlet.class);
+            logger.info("Hello, servlet!");
+        }));
+    }
+}
+        ]]></pre>
+        <p>
+          Alternatively, you can obtain the
+          <a href="../log4j-core/apidocs/org/apache/logging/log4j/web/Log4jWebLifeCycle.html">Log4jWebLifeCycle</a>
+          instance from the <code>ServletContext</code> attributes, call its
<code>setLoggerContext</code> method as
+          the very first line of code in your asynchronous thread, and call its <code>clearLoggerContext</code>
method
+          as the very last line of code in your asynchronous thread. The following code demonstrates
this. It uses the
+          container thread pool to execute asynchronous request processing, passing an anonymous
inner
+          <code>Runnable</code> to the <code>start</code> method.
+        </p>
+        <pre class="prettyprint linenums"><![CDATA[
+import java.io.IOException;
+import javax.servlet.AsyncContext;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+import org.apache.logging.log4j.web.Log4jWebLifeCycle;
+import org.apache.logging.log4j.web.WebLoggerContextUtils;
+
+public class TestAsyncServlet extends HttpServlet {
+    @Override
+    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException {
+         final AsyncContext asyncContext = req.startAsync();
+        asyncContext.start(new Runnable() {
+            @Override
+            public void run() {
+                final Log4jWebLifeCycle webLifeCycle =
+                    WebLoggerContextUtils.getWebLifeCycle(TestAsyncServlet.this.getServletContext());
+                webLifeCycle.setLoggerContext();
                 try {
-                    // miscellaneous asynchronous request handling
+                    final Logger logger = LogManager.getLogger(TestAsyncServlet.class);
+                    logger.info("Hello, servlet!");
                 } finally {
-                    support.clearLoggerContext();
+                    webLifeCycle.clearLoggerContext();
                 }
             }
         });
-    }
-}]]></pre>
+   }
+}
+        ]]></pre>
         <p>
           Note that you <em>must</em> call <code>clearLoggerContext</code>
once your thread is finished
           processing. Failing to do so will result in memory leaks. If using a thread pool,
it can even disrupt the
           logging of other web applications in your container. For that reason, the example
here shows clearing the
-          context in a <code>finally</code> block, which will always execute.
As a shortcut, you can use the
-          <code>wrapExecution</code> method, which takes care of setting the
context, executing the code you pass in,
-          and clearing the context in a finally black. This is especially convenient when
using Java 8 lambdas.
+          context in a <code>finally</code> block, which will always execute.
         </p>
-        <pre class="prettyprint linenums"><![CDATA[public class AsyncServlet extends
HttpServlet
-{
-    @Override
-    protected void doGet(HttpServletRequest request, HttpServletResponse response)
-            throws ServletException, IOException
-    {
-        final AsyncContext context = request.startAsync(request, response);
-        context.setTimeout(timeout);
-        context.start(() -> {
-            Log4jWebSupport support = (Log4jWebSupport)this.getServletContext()
-                    .getAttribute(Log4jWebSupport.SUPPORT_ATTRIBUTE);
-            support.wrapExecution(() -> {
-                // miscellaneous asynchronous request handling
-            });
-        });
-    }
-}]]></pre>
       </subsection>
     </section>
   </body>



Mime
View raw message