Repository: logging-log4j2
Updated Branches:
  refs/heads/master 77364719b -> 2ab1bbcfc


[LOG4J2-1023] New RewritePolicy for changing level of a log event.

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

Branch: refs/heads/master
Commit: 2ab1bbcfcf380004c1b2098cff8ca90fe13059e0
Parents: 7736471
Author: Gary Gregory <[email protected]>
Authored: Wed May 20 20:29:29 2015 -0700
Committer: Gary Gregory <[email protected]>
Committed: Wed May 20 20:29:29 2015 -0700

----------------------------------------------------------------------
 .../rewrite/LoggerNameLevelRewritePolicy.java   | 92 ++++++++++++++++++++
 .../LoggerNameLevelRewritePolicyTest.java       | 61 +++++++++++++
 src/changes/changes.xml                         |  3 +
 src/site/xdoc/manual/appenders.xml              | 51 ++++++++++-
 4 files changed, 205 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/2ab1bbcf/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/rewrite/LoggerNameLevelRewritePolicy.java
----------------------------------------------------------------------
diff --git 
a/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/rewrite/LoggerNameLevelRewritePolicy.java
 
b/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/rewrite/LoggerNameLevelRewritePolicy.java
new file mode 100644
index 0000000..0577373
--- /dev/null
+++ 
b/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/rewrite/LoggerNameLevelRewritePolicy.java
@@ -0,0 +1,92 @@
+/*
+ * 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.appender.rewrite;
+
+import java.util.HashMap;
+import java.util.Locale;
+import java.util.Map;
+
+import org.apache.logging.log4j.Level;
+import org.apache.logging.log4j.core.LogEvent;
+import org.apache.logging.log4j.core.config.plugins.Plugin;
+import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
+import org.apache.logging.log4j.core.config.plugins.PluginElement;
+import org.apache.logging.log4j.core.config.plugins.PluginFactory;
+import org.apache.logging.log4j.core.impl.Log4jLogEvent;
+import org.apache.logging.log4j.core.util.KeyValuePair;
+
+/**
+ * Rewrites log event levels for a given logger name.
+ * 
+ * @since 2.4
+ */
+@Plugin(name = "LevelRewritePolicy", category = "Core", elementType = 
"rewritePolicy", printObject = true)
+public class LoggerNameLevelRewritePolicy implements RewritePolicy {
+
+    /**
+     * Creates a policy to rewrite levels for a given logger name.
+     * 
+     * @param loggerNamePrefix
+     *        The logger name prefix for events to rewrite; all event logger 
names that start with this string will be
+     *        rewritten.
+     * @param levelPairs
+     *        The levels to rewrite, the key is the source level, the value 
the target level.
+     * @return a new LoggerNameLevelRewritePolicy
+     */
+    @PluginFactory
+    public static LoggerNameLevelRewritePolicy createPolicy(
+            // @formatter:off
+            @PluginAttribute("logger") final String loggerNamePrefix,
+            @PluginElement("LevelPair") final KeyValuePair[] levelPairs) {
+            // @formatter:on
+        Map<Level, Level> newMap = new HashMap<>(levelPairs.length);
+        for (KeyValuePair keyValuePair : levelPairs) {
+            newMap.put(getLevel(keyValuePair.getKey()), 
getLevel(keyValuePair.getValue()));
+        }
+        return new LoggerNameLevelRewritePolicy(loggerNamePrefix, newMap);
+    }
+
+    private static Level getLevel(String name) {
+        return Level.getLevel(name.toUpperCase(Locale.ROOT));
+    }
+
+    private final String loggerName;
+
+    private final Map<Level, Level> map;
+
+    private LoggerNameLevelRewritePolicy(String loggerName, Map<Level, Level> 
map) {
+        super();
+        this.loggerName = loggerName;
+        this.map = map;
+    }
+
+    @Override
+    public LogEvent rewrite(LogEvent event) {
+        if (!event.getLoggerName().startsWith(loggerName)) {
+            return event;
+        }
+        final Level sourceLevel = event.getLevel();
+        final Level newLevel = map.get(sourceLevel);
+        LogEvent result = new Log4jLogEvent(event.getLoggerName(), 
event.getMarker(), event.getLoggerFqcn(),
+                newLevel == null ? sourceLevel : newLevel, event.getMessage(), 
event.getThrown(),
+                event.getContextMap(), event.getContextStack(), 
event.getThreadName(), event.getSource(),
+                event.getTimeMillis());
+
+        return result;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/2ab1bbcf/log4j-core/src/test/java/org/apache/logging/log4j/core/appender/rewrite/LoggerNameLevelRewritePolicyTest.java
----------------------------------------------------------------------
diff --git 
a/log4j-core/src/test/java/org/apache/logging/log4j/core/appender/rewrite/LoggerNameLevelRewritePolicyTest.java
 
b/log4j-core/src/test/java/org/apache/logging/log4j/core/appender/rewrite/LoggerNameLevelRewritePolicyTest.java
new file mode 100644
index 0000000..4e391d9
--- /dev/null
+++ 
b/log4j-core/src/test/java/org/apache/logging/log4j/core/appender/rewrite/LoggerNameLevelRewritePolicyTest.java
@@ -0,0 +1,61 @@
+/*
+ * 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.appender.rewrite;
+
+import org.apache.logging.log4j.Level;
+import org.apache.logging.log4j.core.LogEvent;
+import org.apache.logging.log4j.core.impl.Log4jLogEvent;
+import org.apache.logging.log4j.core.util.KeyValuePair;
+import org.apache.logging.log4j.message.SimpleMessage;
+import org.junit.Assert;
+import org.junit.Test;
+
+/**
+ * Tests {@link LoggerNameLevelRewritePolicy}.
+ * 
+ * @since 2.4
+ */
+public class LoggerNameLevelRewritePolicyTest {
+
+    @Test
+    public void testUpdate() {
+        KeyValuePair[] rewrite = new KeyValuePair[] {
+                new KeyValuePair("INFO", "DEBUG"),
+                new KeyValuePair("WARN", "INFO") };
+        final String loggerNameRewrite = "com.foo.bar";
+        LogEvent logEvent = new Log4jLogEvent(loggerNameRewrite, null, 
"LoggerNameLevelRewritePolicyTest.testUpdate()",
+                Level.INFO, new SimpleMessage("Test"), new 
RuntimeException("test"), null, null, "none", null, 1);
+        final LoggerNameLevelRewritePolicy updatePolicy = 
LoggerNameLevelRewritePolicy.createPolicy(loggerNameRewrite,
+                rewrite);
+        LogEvent rewritten = updatePolicy.rewrite(logEvent);
+        Assert.assertEquals(Level.DEBUG, rewritten.getLevel());
+        logEvent = new Log4jLogEvent(loggerNameRewrite, null, 
"LoggerNameLevelRewritePolicyTest.testUpdate()",
+                Level.WARN, new SimpleMessage("Test"), new 
RuntimeException("test"), null, null, "none", null, 1);
+        rewritten = updatePolicy.rewrite(logEvent);
+        Assert.assertEquals(Level.INFO, rewritten.getLevel());
+        final String loggerNameReadOnly = "com.nochange";
+        logEvent = new Log4jLogEvent(loggerNameReadOnly, null, 
"LoggerNameLevelRewritePolicyTest.testUpdate()",
+                Level.INFO, new SimpleMessage("Test"), new 
RuntimeException("test"), null, null, "none", null, 1);
+        rewritten = updatePolicy.rewrite(logEvent);
+        Assert.assertEquals(Level.INFO, rewritten.getLevel());
+        logEvent = new Log4jLogEvent(loggerNameReadOnly, null, 
"LoggerNameLevelRewritePolicyTest.testUpdate()",
+                Level.WARN, new SimpleMessage("Test"), new 
RuntimeException("test"), null, null, "none", null, 1);
+        rewritten = updatePolicy.rewrite(logEvent);
+        Assert.assertEquals(Level.WARN, rewritten.getLevel());
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/2ab1bbcf/src/changes/changes.xml
----------------------------------------------------------------------
diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index 25a0f19..4d5362e 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -24,6 +24,9 @@
   </properties>
   <body>
     <release version="2.4" date="2015-MM-DD" description="GA Release 2.4">
+      <action issue="LOG4J2-1023" dev="ggregory" type="add" due-to="Mikael 
Ståldal">
+        New RewritePolicy for changing level of a log event.
+      </action>
       <action issue="LOG4J2-1015" dev="ggregory" type="add">
         Add a way to route messages based on the %marker in Layout for 
RoutingAppender.
       </action>

http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/2ab1bbcf/src/site/xdoc/manual/appenders.xml
----------------------------------------------------------------------
diff --git a/src/site/xdoc/manual/appenders.xml 
b/src/site/xdoc/manual/appenders.xml
index 7b12d83..1aaafb3 100644
--- a/src/site/xdoc/manual/appenders.xml
+++ b/src/site/xdoc/manual/appenders.xml
@@ -1888,9 +1888,8 @@ public class JpaLogEntity extends 
AbstractLogEventWrapperEntity {
           </table>
           <p>
             The following configuration shows a RewriteAppender configured to 
add a product key and its value
-            to the MapMessage.:
+            to the MapMessage:
           </p>
-
             <pre class="prettyprint linenums"><![CDATA[<?xml version="1.0" 
encoding="UTF-8"?>
 <Configuration status="warn" name="MyApp" packages="">
   <Appenders>
@@ -1911,6 +1910,54 @@ public class JpaLogEntity extends 
AbstractLogEventWrapperEntity {
     </Root>
   </Loggers>
 </Configuration>]]></pre>
+        <h5>LoggerNameLevelRewritePolicy</h5>
+        <p>
+          You can use this policy to make loggers in third party code less 
chatty by changing event levels.
+          The LoggerNameLevelRewritePolicy will rewrite log event levels for a 
given logger name prefix.
+          You configure a LoggerNameLevelRewritePolicy with a logger name 
prefix and a pairs of levels, 
+          where a pair defines a source level and a target level.
+        </p>
+          <table>
+            <tr>
+              <th>Parameter Name</th>
+              <th>Type</th>
+              <th>Description</th>
+            </tr>
+            <tr>
+              <td>loggerName</td>
+              <td>String</td>
+              <td>A logger name used as a prefix to test each event's logger 
name.</td>
+            </tr>
+            <tr>
+              <td>levelPair</td>
+              <td>KeyValuePair[]</td>
+              <td>An array of keys and their values, each key is a source 
level, each value a target level.</td>
+            </tr>
+          </table>
+          <p>
+            The following configuration shows a RewriteAppender configured to 
map level INFO to DEBUG and level 
+            WARN to INFO for all loggers that start with 
<code>com.foo.bar</code>. 
+          </p>
+            <pre class="prettyprint linenums"><![CDATA[<?xml version="1.0" 
encoding="UTF-8"?>
+<Configuration status="warn" name="MyApp">
+  <Appenders>
+    <Console name="STDOUT" target="SYSTEM_OUT">
+      <PatternLayout pattern="%m%n"/>
+    </Console>
+    <Rewrite name="rewrite">
+      <AppenderRef ref="STDOUT"/>
+      <LoggerNameLevelRewritePolicy loggerName="com.foo.bar">
+        <LevelPair key="INFO" value="DEBUG"/>
+        <LevelPair key="WARN" value="INFO"/>
+      </LoggerNameLevelRewritePolicy>
+    </Rewrite>
+  </Appenders>
+  <Loggers>
+    <Root level="error">
+      <AppenderRef ref="Rewrite"/>
+    </Root>
+  </Loggers>
+</Configuration>]]></pre>
         </subsection>
         <a name="RollingFileAppender"/>
         <subsection name="RollingFileAppender">

Reply via email to