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.PluginFactory;
026    import org.apache.logging.log4j.message.Message;
027    
028    import java.util.regex.Matcher;
029    import java.util.regex.Pattern;
030    
031    /**
032     * This filter returns the onMatch result if the message matches the regular expression.
033     *
034     * The "useRawMsg" attribute can be used to indicate whether the regular expression should be
035     * applied to the result of calling Message.getMessageFormat (true) or Message.getFormattedMessage()
036     * (false). The default is false.
037     *
038     */
039    @Plugin(name = "RegexFilter", category = "Core", elementType = "filter", printObject = true)
040    public final class RegexFilter extends AbstractFilter {
041    
042        private final Pattern pattern;
043        private final boolean useRawMessage;
044    
045        private RegexFilter(final boolean raw, final Pattern pattern, final Result onMatch, final Result onMismatch) {
046            super(onMatch, onMismatch);
047            this.pattern = pattern;
048            this.useRawMessage = raw;
049        }
050    
051        @Override
052        public Result filter(final Logger logger, final Level level, final Marker marker, final String msg,
053                             final Object... params) {
054            return filter(msg);
055        }
056    
057        @Override
058        public Result filter(final Logger logger, final Level level, final Marker marker, final Object msg,
059                             final Throwable t) {
060            if (msg == null) {
061                return onMismatch;
062            }
063            return filter(msg.toString());
064        }
065    
066        @Override
067        public Result filter(final Logger logger, final Level level, final Marker marker, final Message msg,
068                             final Throwable t) {
069            if (msg == null) {
070                return onMismatch;
071            }
072            final String text = useRawMessage ? msg.getFormat() : msg.getFormattedMessage();
073            return filter(text);
074        }
075    
076        @Override
077        public Result filter(final LogEvent event) {
078            final String text = useRawMessage ? event.getMessage().getFormat() : event.getMessage().getFormattedMessage();
079            return filter(text);
080        }
081    
082        private Result filter(final String msg) {
083            if (msg == null) {
084                return onMismatch;
085            }
086            final Matcher m = pattern.matcher(msg);
087            return m.matches() ? onMatch : onMismatch;
088        }
089    
090        @Override
091        public String toString() {
092            final StringBuilder sb = new StringBuilder();
093            sb.append("useRaw=").append(useRawMessage);
094            sb.append(", pattern=").append(pattern.toString());
095            return sb.toString();
096        }
097    
098        /**
099         * Create a Filter that matches a regular expression.
100         * @param regex The regular expression to match.
101         * @param useRawMsg If true, the raw message will be used, otherwise the formatted message will be used.
102         * @param match The action to perform when a match occurs.
103         * @param mismatch The action to perform when a mismatch occurs.
104         * @return The RegexFilter.
105         */
106        @PluginFactory
107        public static RegexFilter createFilter(@PluginAttr("regex") final String regex,
108                                               @PluginAttr("useRawMsg") final String useRawMsg,
109                                                @PluginAttr("onMatch") final String match,
110                                                @PluginAttr("onMismatch") final String mismatch) {
111    
112            if (regex == null) {
113                LOGGER.error("A regular expression must be provided for RegexFilter");
114                return null;
115            }
116            final boolean raw = useRawMsg == null ? false : Boolean.parseBoolean(useRawMsg);
117            Pattern pattern;
118            try {
119                pattern = Pattern.compile(regex);
120            } catch (final Exception ex) {
121                LOGGER.error("RegexFilter caught exception compiling pattern: " + regex + " cause: " + ex.getMessage());
122                return null;
123            }
124            final Result onMatch = Result.toResult(match);
125            final Result onMismatch = Result.toResult(mismatch);
126    
127            return new RegexFilter(raw, pattern, onMatch, onMismatch);
128        }
129    
130    }