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