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.List;
022import java.util.Map;
023
024import org.apache.logging.log4j.Level;
025import org.apache.logging.log4j.Marker;
026import org.apache.logging.log4j.core.Filter;
027import org.apache.logging.log4j.core.LogEvent;
028import org.apache.logging.log4j.core.Logger;
029import org.apache.logging.log4j.core.config.Node;
030import org.apache.logging.log4j.core.config.plugins.Plugin;
031import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
032import org.apache.logging.log4j.core.config.plugins.PluginElement;
033import org.apache.logging.log4j.core.config.plugins.PluginFactory;
034import org.apache.logging.log4j.core.util.KeyValuePair;
035import org.apache.logging.log4j.message.Message;
036import org.apache.logging.log4j.message.StructuredDataMessage;
037import org.apache.logging.log4j.util.IndexedReadOnlyStringMap;
038import org.apache.logging.log4j.util.PerformanceSensitive;
039import org.apache.logging.log4j.util.StringBuilders;
040
041/**
042 * Filter based on data in a StructuredDataMessage.
043 */
044@Plugin(name = "StructuredDataFilter", category = Node.CATEGORY, elementType = Filter.ELEMENT_TYPE, printObject = true)
045@PerformanceSensitive("allocation")
046public final class StructuredDataFilter extends MapFilter {
047
048    private static final int MAX_BUFFER_SIZE = 2048;
049    private static ThreadLocal<StringBuilder> threadLocalStringBuilder = new ThreadLocal<>();
050
051    private StructuredDataFilter(final Map<String, List<String>> map, final boolean oper, final Result onMatch,
052                                 final Result onMismatch) {
053        super(map, oper, onMatch, onMismatch);
054    }
055
056    @Override
057    public Result filter(final Logger logger, final Level level, final Marker marker, final Message msg,
058                         final Throwable t) {
059        if (msg instanceof StructuredDataMessage) {
060            return filter((StructuredDataMessage) msg);
061        }
062        return Result.NEUTRAL;
063    }
064
065    @Override
066    public Result filter(final LogEvent event) {
067        final Message msg = event.getMessage();
068        if (msg instanceof StructuredDataMessage) {
069            return filter((StructuredDataMessage) msg);
070        }
071        return super.filter(event);
072    }
073
074    protected Result filter(final StructuredDataMessage message) {
075        boolean match = false;
076        final IndexedReadOnlyStringMap map = getStringMap();
077        for (int i = 0; i < map.size(); i++) {
078            final StringBuilder toMatch = getValue(message, map.getKeyAt(i));
079            if (toMatch != null) {
080                match = listContainsValue((List<String>) map.getValueAt(i), toMatch);
081            } else {
082                match = false;
083            }
084            if ((!isAnd() && match) || (isAnd() && !match)) {
085                break;
086            }
087        }
088        return match ? onMatch : onMismatch;
089    }
090
091    private StringBuilder getValue(final StructuredDataMessage data, final String key) {
092        final StringBuilder sb = getStringBuilder();
093        if (key.equalsIgnoreCase("id")) {
094            data.getId().formatTo(sb);
095            return sb;
096        } else if (key.equalsIgnoreCase("id.name")) {
097            return appendOrNull(data.getId().getName(), sb);
098        } else if (key.equalsIgnoreCase("type")) {
099            return appendOrNull(data.getType(), sb);
100        } else if (key.equalsIgnoreCase("message")) {
101            data.formatTo(sb);
102            return sb;
103        } else {
104            return appendOrNull(data.get(key), sb);
105        }
106    }
107
108    private StringBuilder getStringBuilder() {
109        StringBuilder result = threadLocalStringBuilder.get();
110        if (result == null) {
111            result = new StringBuilder();
112            threadLocalStringBuilder.set(result);
113        }
114        if (result.length() > MAX_BUFFER_SIZE) {
115            result.setLength(MAX_BUFFER_SIZE);
116            result.trimToSize();
117        }
118        result.setLength(0);
119        return result;
120    }
121
122    private StringBuilder appendOrNull(final String value, final StringBuilder sb) {
123        if (value == null) {
124            return null;
125        }
126        sb.append(value);
127        return sb;
128    }
129
130    private boolean listContainsValue(final List<String> candidates, final StringBuilder toMatch) {
131        if (toMatch == null) {
132            for (int i = 0; i < candidates.size(); i++) {
133                final String candidate = candidates.get(i);
134                if (candidate == null) {
135                    return true;
136                }
137            }
138        } else {
139            for (int i = 0; i < candidates.size(); i++) {
140                final String candidate = candidates.get(i);
141                if (candidate == null) {
142                    return false;
143                }
144                if (StringBuilders.equals(candidate, 0, candidate.length(), toMatch, 0, toMatch.length())) {
145                    return true;
146                }
147            }
148        }
149        return false;
150    }
151
152    /**
153     * Create the StructuredDataFilter.
154     * @param pairs Key and value pairs.
155     * @param oper The operator to perform. If not "or" the operation will be an "and".
156     * @param match The action to perform on a match.
157     * @param mismatch The action to perform on a mismatch.
158     * @return The StructuredDataFilter.
159     */
160    @PluginFactory
161    public static StructuredDataFilter createFilter(
162            @PluginElement("Pairs") final KeyValuePair[] pairs,
163            @PluginAttribute("operator") final String oper,
164            @PluginAttribute("onMatch") final Result match,
165            @PluginAttribute("onMismatch") final Result mismatch) {
166        if (pairs == null || pairs.length == 0) {
167            LOGGER.error("keys and values must be specified for the StructuredDataFilter");
168            return null;
169        }
170        final Map<String, List<String>> map = new HashMap<>();
171        for (final KeyValuePair pair : pairs) {
172            final String key = pair.getKey();
173            if (key == null) {
174                LOGGER.error("A null key is not valid in MapFilter");
175                continue;
176            }
177            final String value = pair.getValue();
178            if (value == null) {
179                LOGGER.error("A null value for key " + key + " is not allowed in MapFilter");
180                continue;
181            }
182            List<String> list = map.get(pair.getKey());
183            if (list != null) {
184                list.add(value);
185            } else {
186                list = new ArrayList<>();
187                list.add(value);
188                map.put(pair.getKey(), list);
189            }
190        }
191        if (map.isEmpty()) {
192            LOGGER.error("StructuredDataFilter is not configured with any valid key value pairs");
193            return null;
194        }
195        final boolean isAnd = oper == null || !oper.equalsIgnoreCase("or");
196        return new StructuredDataFilter(map, isAnd, match, mismatch);
197    }
198}