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