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 org.apache.logging.log4j.Level;
020    import org.apache.logging.log4j.Marker;
021    import org.apache.logging.log4j.core.LogEvent;
022    import org.apache.logging.log4j.core.Logger;
023    import org.apache.logging.log4j.core.config.plugins.Plugin;
024    import org.apache.logging.log4j.core.config.plugins.PluginAttr;
025    import org.apache.logging.log4j.core.config.plugins.PluginElement;
026    import org.apache.logging.log4j.core.config.plugins.PluginFactory;
027    import org.apache.logging.log4j.core.helpers.KeyValuePair;
028    import org.apache.logging.log4j.message.Message;
029    import org.apache.logging.log4j.message.StructuredDataMessage;
030    
031    import java.util.ArrayList;
032    import java.util.HashMap;
033    import java.util.List;
034    import java.util.Map;
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(@PluginElement("pairs") final KeyValuePair[] pairs,
105                                                        @PluginAttr("operator") final String oper,
106                                                        @PluginAttr("onmatch") final String match,
107                                                        @PluginAttr("onmismatch") final String mismatch) {
108            if (pairs == null || pairs.length == 0) {
109                LOGGER.error("keys and values must be specified for the StructuredDataFilter");
110                return null;
111            }
112            final Map<String, List<String>> map = new HashMap<String, List<String>>();
113            for (final KeyValuePair pair : pairs) {
114                final String key = pair.getKey();
115                if (key == null) {
116                    LOGGER.error("A null key is not valid in MapFilter");
117                    continue;
118                }
119                final String value = pair.getValue();
120                if (value == null) {
121                    LOGGER.error("A null value for key " + key + " is not allowed in MapFilter");
122                    continue;
123                }
124                List<String> list = map.get(pair.getKey());
125                if (list != null) {
126                    list.add(value);
127                } else {
128                    list = new ArrayList<String>();
129                    list.add(value);
130                    map.put(pair.getKey(), list);
131                }
132            }
133            if (map.size() == 0) {
134                LOGGER.error("StructuredDataFilter is not configured with any valid key value pairs");
135                return null;
136            }
137            final boolean isAnd = oper == null || !oper.equalsIgnoreCase("or");
138            final Result onMatch = Result.toResult(match);
139            final Result onMismatch = Result.toResult(mismatch);
140            return new StructuredDataFilter(map, isAnd, onMatch, onMismatch);
141        }
142    }