View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements. See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache license, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License. You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the license for the specific language governing permissions and
15   * limitations under the license.
16   */
17  package org.apache.logging.log4j.core.filter;
18  
19  import org.apache.logging.log4j.Level;
20  import org.apache.logging.log4j.Marker;
21  import org.apache.logging.log4j.ThreadContext;
22  import org.apache.logging.log4j.core.LogEvent;
23  import org.apache.logging.log4j.core.Logger;
24  import org.apache.logging.log4j.core.config.plugins.Plugin;
25  import org.apache.logging.log4j.core.config.plugins.PluginAttr;
26  import org.apache.logging.log4j.core.config.plugins.PluginElement;
27  import org.apache.logging.log4j.core.config.plugins.PluginFactory;
28  import org.apache.logging.log4j.core.helpers.KeyValuePair;
29  import org.apache.logging.log4j.message.Message;
30  
31  import java.util.HashMap;
32  import java.util.Map;
33  
34  /**
35   * Compare against a log level that is associated with an MDC value.
36   */
37  @Plugin(name = "DynamicThresholdFilter", category = "Core", elementType = "filter", printObject = true)
38  public final class DynamicThresholdFilter extends AbstractFilter {
39      private Map<String, Level> levelMap = new HashMap<String, Level>();
40      private Level defaultThreshold = Level.ERROR;
41      private final String key;
42  
43      private DynamicThresholdFilter(final String key, final Map<String, Level> pairs, final Level defaultLevel,
44                                     final Result onMatch, final Result onMismatch) {
45          super(onMatch, onMismatch);
46          if (key == null) {
47              throw new NullPointerException("key cannot be null");
48          }
49          this.key = key;
50          this.levelMap = pairs;
51          this.defaultThreshold = defaultLevel;
52      }
53  
54      public String getKey() {
55          return this.key;
56      }
57  
58      @Override
59      public Result filter(final Logger logger, final Level level, final Marker marker, final String msg,
60                           final Object... params) {
61          return filter(level);
62      }
63  
64      @Override
65      public Result filter(final Logger logger, final Level level, final Marker marker, final Object msg,
66                           final Throwable t) {
67          return filter(level);
68      }
69  
70      @Override
71      public Result filter(final Logger logger, final Level level, final Marker marker, final Message msg,
72                           final Throwable t) {
73          return filter(level);
74      }
75  
76      @Override
77      public Result filter(final LogEvent event) {
78          return filter(event.getLevel());
79      }
80  
81      private Result filter(final Level level) {
82          final Object value = ThreadContext.get(key);
83          if (value != null) {
84              Level ctxLevel = levelMap.get(value);
85              if (ctxLevel == null) {
86                  ctxLevel = defaultThreshold;
87              }
88              return level.isAtLeastAsSpecificAs(ctxLevel) ? onMatch : onMismatch;
89          }
90          return Result.NEUTRAL;
91  
92      }
93  
94      public Map<String, Level> getLevelMap() {
95          return levelMap;
96      }
97  
98      @Override
99      public String toString() {
100         final StringBuilder sb = new StringBuilder();
101         sb.append("key=").append(key);
102         sb.append(", default=").append(defaultThreshold);
103         if (levelMap.size() > 0) {
104             sb.append("{");
105             boolean first = true;
106             for (final Map.Entry<String, Level> entry : levelMap.entrySet()) {
107                 if (!first) {
108                     sb.append(", ");
109                     first = false;
110                 }
111                 sb.append(entry.getKey()).append("=").append(entry.getValue());
112             }
113             sb.append("}");
114         }
115         return sb.toString();
116     }
117 
118     /**
119      * Create the DynamicThresholdFilter.
120      * @param key The name of the key to compare.
121      * @param pairs An array of value and Level pairs.
122      * @param levelName The default Level.
123      * @param match The action to perform if a match occurs.
124      * @param mismatch The action to perform if no match occurs.
125      * @return The DynamicThresholdFilter.
126      */
127     @PluginFactory
128     public static DynamicThresholdFilter createFilter(@PluginAttr("key") final String key,
129                                                       @PluginElement("pairs") final KeyValuePair[] pairs,
130                                                       @PluginAttr("defaultThreshold") final String levelName,
131                                                       @PluginAttr("onmatch") final String match,
132                                                       @PluginAttr("onmismatch") final String mismatch) {
133         final Result onMatch = Result.toResult(match);
134         final Result onMismatch = Result.toResult(mismatch);
135         final Map<String, Level> map = new HashMap<String, Level>();
136         for (final KeyValuePair pair : pairs) {
137             map.put(pair.getKey(), Level.toLevel(pair.getValue()));
138         }
139         final Level level = Level.toLevel(levelName, Level.ERROR);
140         return new DynamicThresholdFilter(key, map, level, onMatch, onMismatch);
141     }
142 }