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