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;
037
038/**
039 * Filter based on data in a StructuredDataMessage.
040 */
041@Plugin(name = "StructuredDataFilter", category = Node.CATEGORY, elementType = Filter.ELEMENT_TYPE, printObject = true)
042public final class StructuredDataFilter extends MapFilter {
043
044    private StructuredDataFilter(final Map<String, List<String>> map, final boolean oper, final Result onMatch,
045                                 final Result onMismatch) {
046        super(map, oper, onMatch, onMismatch);
047    }
048
049    @Override
050    public Result filter(final Logger logger, final Level level, final Marker marker, final Message msg,
051                         final Throwable t) {
052        if (msg instanceof StructuredDataMessage) {
053            return filter((StructuredDataMessage) msg);
054        }
055        return Result.NEUTRAL;
056    }
057
058    @Override
059    public Result filter(final LogEvent event) {
060        final Message msg = event.getMessage();
061        if (msg instanceof StructuredDataMessage) {
062            return filter((StructuredDataMessage) msg);
063        }
064        return super.filter(event);
065    }
066
067    protected Result filter(final StructuredDataMessage message) {
068        boolean match = false;
069        for (final Map.Entry<String, List<String>> entry : getMap().entrySet()) {
070            final String toMatch = getValue(message, entry.getKey());
071            if (toMatch != null) {
072                match = entry.getValue().contains(toMatch);
073            } else {
074                match = false;
075            }
076            if ((!isAnd() && match) || (isAnd() && !match)) {
077                break;
078            }
079        }
080        return match ? onMatch : onMismatch;
081    }
082
083    private String getValue(final StructuredDataMessage data, final String key) {
084        if (key.equalsIgnoreCase("id")) {
085            return data.getId().toString();
086        } else if (key.equalsIgnoreCase("id.name")) {
087            return data.getId().getName();
088        } else if (key.equalsIgnoreCase("type")) {
089            return data.getType();
090        } else if (key.equalsIgnoreCase("message")) {
091            return data.getFormattedMessage();
092        } else {
093            return data.getData().get(key);
094        }
095    }
096
097    /**
098     * Create the StructuredDataFilter.
099     * @param pairs Key and value pairs.
100     * @param oper The operator to perform. If not "or" the operation will be an "and".
101     * @param match The action to perform on a match.
102     * @param mismatch The action to perform on a mismatch.
103     * @return The StructuredDataFilter.
104     */
105    @PluginFactory
106    public static StructuredDataFilter createFilter(
107            @PluginElement("Pairs") final KeyValuePair[] pairs,
108            @PluginAttribute("operator") final String oper,
109            @PluginAttribute("onMatch") final Result match,
110            @PluginAttribute("onMismatch") final Result mismatch) {
111        if (pairs == null || pairs.length == 0) {
112            LOGGER.error("keys and values must be specified for the StructuredDataFilter");
113            return null;
114        }
115        final Map<String, List<String>> map = new HashMap<>();
116        for (final KeyValuePair pair : pairs) {
117            final String key = pair.getKey();
118            if (key == null) {
119                LOGGER.error("A null key is not valid in MapFilter");
120                continue;
121            }
122            final String value = pair.getValue();
123            if (value == null) {
124                LOGGER.error("A null value for key " + key + " is not allowed in MapFilter");
125                continue;
126            }
127            List<String> list = map.get(pair.getKey());
128            if (list != null) {
129                list.add(value);
130            } else {
131                list = new ArrayList<>();
132                list.add(value);
133                map.put(pair.getKey(), list);
134            }
135        }
136        if (map.isEmpty()) {
137            LOGGER.error("StructuredDataFilter is not configured with any valid key value pairs");
138            return null;
139        }
140        final boolean isAnd = oper == null || !oper.equalsIgnoreCase("or");
141        return new StructuredDataFilter(map, isAnd, match, mismatch);
142    }
143}