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 */
017package org.apache.logging.log4j.core.filter;
018
019import java.util.ArrayList;
020import java.util.HashMap;
021import java.util.Iterator;
022import java.util.List;
023import java.util.Map;
024
025import org.apache.logging.log4j.Level;
026import org.apache.logging.log4j.Marker;
027import org.apache.logging.log4j.ThreadContext;
028import org.apache.logging.log4j.core.Filter;
029import org.apache.logging.log4j.core.LogEvent;
030import org.apache.logging.log4j.core.Logger;
031import org.apache.logging.log4j.core.config.Node;
032import org.apache.logging.log4j.core.config.plugins.Plugin;
033import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
034import org.apache.logging.log4j.core.config.plugins.PluginElement;
035import org.apache.logging.log4j.core.config.plugins.PluginFactory;
036import org.apache.logging.log4j.core.util.KeyValuePair;
037import org.apache.logging.log4j.message.Message;
038
039/**
040 * Filter based on a value in the Thread Context Map (MDC).
041 */
042@Plugin(name = "ThreadContextMapFilter", category = Node.CATEGORY, elementType = Filter.ELEMENT_TYPE, printObject = true)
043public class ThreadContextMapFilter extends MapFilter {
044
045    private final String key;
046    private final String value;
047
048    private final boolean useMap;
049
050    public ThreadContextMapFilter(final Map<String, List<String>> pairs, final boolean oper, final Result onMatch,
051                                  final Result onMismatch) {
052        super(pairs, oper, onMatch, onMismatch);
053        if (pairs.size() == 1) {
054            final Iterator<Map.Entry<String, List<String>>> iter = pairs.entrySet().iterator();
055            final Map.Entry<String, List<String>> entry = iter.next();
056            if (entry.getValue().size() == 1) {
057                this.key = entry.getKey();
058                this.value = entry.getValue().get(0);
059                this.useMap = false;
060            } else {
061                this.key = null;
062                this.value = null;
063                this.useMap = true;
064            }
065        } else {
066            this.key = null;
067            this.value = null;
068            this.useMap = true;
069        }
070    }
071
072    @Override
073    public Result filter(final Logger logger, final Level level, final Marker marker, final String msg,
074                         final Object... params) {
075        return filter();
076    }
077
078    @Override
079    public Result filter(final Logger logger, final Level level, final Marker marker, final Object msg,
080                         final Throwable t) {
081        return filter();
082    }
083
084    @Override
085    public Result filter(final Logger logger, final Level level, final Marker marker, final Message msg,
086                         final Throwable t) {
087        return filter();
088    }
089
090    private Result filter() {
091        boolean match = false;
092        if (useMap) {
093            for (final Map.Entry<String, List<String>> entry : getMap().entrySet()) {
094                final String toMatch = ThreadContext.get(entry.getKey());
095                if (toMatch != null) {
096                    match = entry.getValue().contains(toMatch);
097                } else {
098                    match = false;
099                }
100                if ((!isAnd() && match) || (isAnd() && !match)) {
101                    break;
102                }
103            }
104        } else {
105            match = value.equals(ThreadContext.get(key));
106        }
107        return match ? onMatch : onMismatch;
108    }
109
110    @Override
111    public Result filter(final LogEvent event) {
112        return super.filter(event.getContextMap()) ? onMatch : onMismatch;
113    }
114
115    @PluginFactory
116    public static ThreadContextMapFilter createFilter(
117            @PluginElement("Pairs") final KeyValuePair[] pairs,
118            @PluginAttribute("operator") final String oper,
119            @PluginAttribute("onMatch") final Result match,
120            @PluginAttribute("onMismatch") final Result mismatch) {
121        if (pairs == null || pairs.length == 0) {
122            LOGGER.error("key and value pairs must be specified for the ThreadContextMapFilter");
123            return null;
124        }
125        final Map<String, List<String>> map = new HashMap<>();
126        for (final KeyValuePair pair : pairs) {
127            final String key = pair.getKey();
128            if (key == null) {
129                LOGGER.error("A null key is not valid in MapFilter");
130                continue;
131            }
132            final String value = pair.getValue();
133            if (value == null) {
134                LOGGER.error("A null value for key " + key + " is not allowed in MapFilter");
135                continue;
136            }
137            List<String> list = map.get(pair.getKey());
138            if (list != null) {
139                list.add(value);
140            } else {
141                list = new ArrayList<>();
142                list.add(value);
143                map.put(pair.getKey(), list);
144            }
145        }
146        if (map.isEmpty()) {
147            LOGGER.error("ThreadContextMapFilter is not configured with any valid key value pairs");
148            return null;
149        }
150        final boolean isAnd = oper == null || !oper.equalsIgnoreCase("or");
151        return new ThreadContextMapFilter(map, isAnd, match, mismatch);
152    }
153}