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