001    /*
002     * Licensed to the Apache Software Foundation (ASF) under one or more
003     * contributor license agreements. See the NOTICE file distributed with
004     * this work for additional information regarding copyright ownership.
005     * The ASF licenses this file to You under the Apache license, Version 2.0
006     * (the "License"); you may not use this file except in compliance with
007     * the License. You may obtain a copy of the License at
008     *
009     *      http://www.apache.org/licenses/LICENSE-2.0
010     *
011     * Unless required by applicable law or agreed to in writing, software
012     * distributed under the License is distributed on an "AS IS" BASIS,
013     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     * See the license for the specific language governing permissions and
015     * limitations under the license.
016     */
017    package org.apache.logging.log4j.core.filter;
018    
019    import org.apache.logging.log4j.Level;
020    import org.apache.logging.log4j.ThreadContext;
021    import org.apache.logging.log4j.Marker;
022    import org.apache.logging.log4j.core.LogEvent;
023    import org.apache.logging.log4j.core.Logger;
024    import org.apache.logging.log4j.core.config.plugins.Plugin;
025    import org.apache.logging.log4j.core.config.plugins.PluginAttr;
026    import org.apache.logging.log4j.core.config.plugins.PluginElement;
027    import org.apache.logging.log4j.core.config.plugins.PluginFactory;
028    import org.apache.logging.log4j.core.helpers.KeyValuePair;
029    import org.apache.logging.log4j.message.Message;
030    
031    import java.util.ArrayList;
032    import java.util.HashMap;
033    import java.util.Iterator;
034    import java.util.List;
035    import java.util.Locale;
036    import java.util.Map;
037    
038    /**
039     * Filter based on a value in the Thread Context Map (MDC).
040     */
041    @Plugin(name = "ThreadContextMapFilter", type = "Core", elementType = "filter", printObject = true)
042    public class ThreadContextMapFilter extends MapFilter {
043    
044        private final String key;
045        private final String value;
046    
047        private final boolean useMap;
048    
049        public ThreadContextMapFilter(Map<String, List<String>> pairs, boolean oper, Result onMatch, Result onMismatch) {
050            super(pairs, oper, onMatch, onMismatch);
051            if (pairs.size() == 1) {
052                Iterator<Map.Entry<String, List<String>>> iter = pairs.entrySet().iterator();
053                Map.Entry<String, List<String>> entry = iter.next();
054                if (entry.getValue().size() == 1) {
055                    this.key = entry.getKey();
056                    this.value = entry.getValue().get(0);
057                    this.useMap = false;
058                } else {
059                    this.key = null;
060                    this.value = null;
061                    this.useMap = true;
062                }
063            } else {
064                this.key = null;
065                this.value = null;
066                this.useMap = true;
067            }
068        }
069    
070        @Override
071        public Result filter(Logger logger, Level level, Marker marker, String msg, Object[] params) {
072            return filter();
073        }
074    
075        @Override
076        public Result filter(Logger logger, Level level, Marker marker, Object msg, Throwable t) {
077            return filter();
078        }
079    
080        @Override
081        public Result filter(Logger logger, Level level, Marker marker, Message msg, Throwable t) {
082            return filter();
083        }
084    
085        private Result filter() {
086            boolean match = false;
087            if (useMap) {
088                for (Map.Entry<String, List<String>> entry : getMap().entrySet()) {
089                    String toMatch = ThreadContext.get(entry.getKey());
090                    if (toMatch != null) {
091                        match = entry.getValue().contains(toMatch);
092                    } else {
093                        match = false;
094                    }
095                    if ((!isAnd() && match) || (isAnd() && !match)) {
096                        break;
097                    }
098                }
099            } else {
100                match = key.equals(ThreadContext.get(key));
101            }
102            return match ? onMatch : onMismatch;
103        }
104    
105        @Override
106        public Result filter(LogEvent event) {
107            return super.filter(event.getContextMap()) ? onMatch : onMismatch;
108        }
109    
110        @PluginFactory
111        public static ThreadContextMapFilter createFilter(@PluginElement("pairs") KeyValuePair[] pairs,
112                                                          @PluginAttr("operator") String oper,
113                                                          @PluginAttr("onmatch") String match,
114                                                          @PluginAttr("onmismatch") String mismatch) {
115            if (pairs == null || pairs.length == 0) {
116                LOGGER.error("key and value pairs must be specified for the ThreadContextMapFilter");
117                return null;
118            }
119            Map<String, List<String>> map = new HashMap<String, List<String>>();
120            for (KeyValuePair pair : pairs) {
121                String key = pair.getKey();
122                if (key == null) {
123                    LOGGER.error("A null key is not valid in MapFilter");
124                    continue;
125                }
126                String value = pair.getValue();
127                if (value == null) {
128                    LOGGER.error("A null value for key " + key + " is not allowed in MapFilter");
129                    continue;
130                }
131                List<String> list = map.get(pair.getKey());
132                if (list != null) {
133                    list.add(value);
134                } else {
135                    list = new ArrayList<String>();
136                    list.add(value);
137                    map.put(pair.getKey(), list);
138                }
139            }
140            if (map.size() == 0) {
141                LOGGER.error("ThreadContextMapFilter is not configured with any valid key value pairs");
142                return null;
143            }
144            boolean isAnd = oper == null || !oper.equalsIgnoreCase("or");
145            Result onMatch = Result.toResult(match);
146            Result onMismatch = Result.toResult(mismatch);
147            return new ThreadContextMapFilter(map, isAnd, onMatch, onMismatch);
148        }
149    }