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 java.util.HashMap;
20  import java.util.Map;
21  
22  import org.apache.logging.log4j.Level;
23  import org.apache.logging.log4j.Marker;
24  import org.apache.logging.log4j.ThreadContext;
25  import org.apache.logging.log4j.core.Filter;
26  import org.apache.logging.log4j.core.LogEvent;
27  import org.apache.logging.log4j.core.Logger;
28  import org.apache.logging.log4j.core.config.Node;
29  import org.apache.logging.log4j.core.config.plugins.Plugin;
30  import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
31  import org.apache.logging.log4j.core.config.plugins.PluginElement;
32  import org.apache.logging.log4j.core.config.plugins.PluginFactory;
33  import org.apache.logging.log4j.core.util.KeyValuePair;
34  import org.apache.logging.log4j.message.Message;
35  
36  /**
37   * Compare against a log level that is associated with an MDC value.
38   */
39  @Plugin(name = "DynamicThresholdFilter", category = Node.CATEGORY, elementType = Filter.ELEMENT_TYPE, printObject = true)
40  public final class DynamicThresholdFilter extends AbstractFilter {
41  
42      private static final long serialVersionUID = 1L;
43  
44      /**
45       * Create the DynamicThresholdFilter.
46       * @param key The name of the key to compare.
47       * @param pairs An array of value and Level pairs.
48       * @param defaultThreshold The default Level.
49       * @param onMatch The action to perform if a match occurs.
50       * @param onMismatch The action to perform if no match occurs.
51       * @return The DynamicThresholdFilter.
52       */
53      @PluginFactory
54      public static DynamicThresholdFilter createFilter(
55              @PluginAttribute("key") final String key,
56              @PluginElement("Pairs") final KeyValuePair[] pairs,
57              @PluginAttribute("defaultThreshold") final Level defaultThreshold,
58              @PluginAttribute("onMatch") final Result onMatch,
59              @PluginAttribute("onMismatch") final Result onMismatch) {
60          final Map<String, Level> map = new HashMap<String, Level>();
61          for (final KeyValuePair pair : pairs) {
62              map.put(pair.getKey(), Level.toLevel(pair.getValue()));
63          }
64          final Level level = defaultThreshold == null ? Level.ERROR : defaultThreshold;
65          return new DynamicThresholdFilter(key, map, level, onMatch, onMismatch);
66      }
67      private Level defaultThreshold = Level.ERROR;
68      private final String key;
69  
70      private Map<String, Level> levelMap = new HashMap<String, Level>();
71  
72      private DynamicThresholdFilter(final String key, final Map<String, Level> pairs, final Level defaultLevel,
73                                     final Result onMatch, final Result onMismatch) {
74          super(onMatch, onMismatch);
75          if (key == null) {
76              throw new NullPointerException("key cannot be null");
77          }
78          this.key = key;
79          this.levelMap = pairs;
80          this.defaultThreshold = defaultLevel;
81      }
82  
83      @Override
84      public boolean equals(final Object obj) {
85          if (this == obj) {
86              return true;
87          }
88          if (!super.equals(obj)) {
89              return false;
90          }
91          if (getClass() != obj.getClass()) {
92              return false;
93          }
94          final DynamicThresholdFilter other = (DynamicThresholdFilter) obj;
95          if (defaultThreshold == null) {
96              if (other.defaultThreshold != null) {
97                  return false;
98              }
99          } else if (!defaultThreshold.equals(other.defaultThreshold)) {
100             return false;
101         }
102         if (key == null) {
103             if (other.key != null) {
104                 return false;
105             }
106         } else if (!key.equals(other.key)) {
107             return false;
108         }
109         if (levelMap == null) {
110             if (other.levelMap != null) {
111                 return false;
112             }
113         } else if (!levelMap.equals(other.levelMap)) {
114             return false;
115         }
116         return true;
117     }
118 
119     private Result filter(final Level level) {
120         final Object value = ThreadContext.get(key);
121         if (value != null) {
122             Level ctxLevel = levelMap.get(value);
123             if (ctxLevel == null) {
124                 ctxLevel = defaultThreshold;
125             }
126             return level.isMoreSpecificThan(ctxLevel) ? onMatch : onMismatch;
127         }
128         return Result.NEUTRAL;
129 
130     }
131 
132     @Override
133     public Result filter(final LogEvent event) {
134         return filter(event.getLevel());
135     }
136 
137     @Override
138     public Result filter(final Logger logger, final Level level, final Marker marker, final Message msg,
139                          final Throwable t) {
140         return filter(level);
141     }
142 
143     @Override
144     public Result filter(final Logger logger, final Level level, final Marker marker, final Object msg,
145                          final Throwable t) {
146         return filter(level);
147     }
148 
149     @Override
150     public Result filter(final Logger logger, final Level level, final Marker marker, final String msg,
151                          final Object... params) {
152         return filter(level);
153     }
154 
155     public String getKey() {
156         return this.key;
157     }
158 
159     public Map<String, Level> getLevelMap() {
160         return levelMap;
161     }
162 
163     @Override
164     public int hashCode() {
165         final int prime = 31;
166         int result = super.hashCode();
167         result = prime * result + ((defaultThreshold == null) ? 0 : defaultThreshold.hashCode());
168         result = prime * result + ((key == null) ? 0 : key.hashCode());
169         result = prime * result + ((levelMap == null) ? 0 : levelMap.hashCode());
170         return result;
171     }
172 
173     @Override
174     public String toString() {
175         final StringBuilder sb = new StringBuilder();
176         sb.append("key=").append(key);
177         sb.append(", default=").append(defaultThreshold);
178         if (levelMap.size() > 0) {
179             sb.append('{');
180             boolean first = true;
181             for (final Map.Entry<String, Level> entry : levelMap.entrySet()) {
182                 if (!first) {
183                     sb.append(", ");
184                     first = false;
185                 }
186                 sb.append(entry.getKey()).append('=').append(entry.getValue());
187             }
188             sb.append('}');
189         }
190         return sb.toString();
191     }
192 }