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.message.Message;
29  
30  import java.util.HashMap;
31  import java.util.Map;
32  
33  /**
34   * Compare against a log level that is associated with an MDC value.
35   */
36  @Plugin(name = "DynamicThresholdFilter", type = "Core", elementType = "filter", printObject = true)
37  public final class DynamicThresholdFilter extends FilterBase {
38      private Map<String, Level> levelMap = new HashMap<String, Level>();
39      private Level defaultThreshold = Level.ERROR;
40      private String key;
41  
42      private DynamicThresholdFilter(String key, Map<String, Level> pairs, Level defaultLevel,
43                                     Result onMatch, Result onMismatch) {
44          super(onMatch, onMismatch);
45          if (key == null) {
46              throw new NullPointerException("key cannot be null");
47          }
48          this.key = key;
49          this.levelMap = pairs;
50          this.defaultThreshold = defaultLevel;
51      }
52  
53      public String getKey() {
54          return this.key;
55      }
56  
57      public Result filter(Logger logger, Level level, Marker marker, String msg, Object[] params) {
58          return filter(level);
59      }
60  
61      public Result filter(Logger logger, Level level, Marker marker, Object msg, Throwable t) {
62          return filter(level);
63      }
64  
65      public Result filter(Logger logger, Level level, Marker marker, Message msg, Throwable t) {
66          return filter(level);
67      }
68  
69      @Override
70      public Result filter(LogEvent event) {
71          return filter(event.getLevel());
72      }
73  
74      private Result filter(Level level) {
75          Object value = ThreadContext.get(key);
76          if (value != null) {
77              Level ctxLevel = levelMap.get(value);
78              if (ctxLevel == null) {
79                  ctxLevel = defaultThreshold;
80              }
81              return level.isAtLeastAsSpecificAs(ctxLevel) ? onMatch : onMismatch;
82          }
83          return Result.NEUTRAL;
84  
85      }
86  
87      @Override
88      public String toString() {
89          StringBuilder sb = new StringBuilder();
90          sb.append("key=").append(key);
91          sb.append(", default=").append(defaultThreshold);
92          if (levelMap.size() > 0) {
93              sb.append("{");
94              boolean first = true;
95              for (Map.Entry<String, Level> entry : levelMap.entrySet()) {
96                  if (!first) {
97                      sb.append(", ");
98                      first = false;
99                  }
100                 sb.append(entry.getKey()).append("=").append(entry.getValue());
101             }
102             sb.append("}");
103         }
104         return sb.toString();
105     }
106 
107     /**
108      * Create the DynamicThresholdFilter.
109      * @param key The name of the key to compare.
110      * @param pairs An array of value and Level pairs.
111      * @param level The default Level.
112      * @param match The action to perform if a match occurs.
113      * @param mismatch The action to perform if no match occurs.
114      * @return The DynamicThresholdFilter.
115      */
116     @PluginFactory
117     public static DynamicThresholdFilter createFilter(@PluginAttr("key") String key,
118                                                       @PluginElement("pairs") ValueLevelPair[] pairs,
119                                                       @PluginAttr("defaultThreshold") String level,
120                                                       @PluginAttr("onmatch") String match,
121                                                       @PluginAttr("onmismatch") String mismatch) {
122         Result onMatch = match == null ? null : Result.valueOf(match.toUpperCase());
123         Result onMismatch = mismatch == null ? null : Result.valueOf(mismatch.toUpperCase());
124         Map<String, Level> map = new HashMap<String, Level>();
125         for (ValueLevelPair pair : pairs) {
126             map.put(pair.getKey(), pair.getLevel());
127         }
128         Level l = Level.toLevel(level, Level.ERROR);
129         return new DynamicThresholdFilter(key, map, l, onMatch, onMismatch);
130     }
131 }