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", type = "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            return filter(msg.toString());
061        }
062    
063        @Override
064        public Result filter(final Logger logger, final Level level, final Marker marker, final Message msg,
065                             final Throwable t) {
066            final String text = useRawMessage ? msg.getFormat() : msg.getFormattedMessage();
067            return filter(text);
068        }
069    
070        @Override
071        public Result filter(final LogEvent event) {
072            final String text = useRawMessage ? event.getMessage().getFormat() : event.getMessage().getFormattedMessage();
073            return filter(text);
074        }
075    
076        private Result filter(final String msg) {
077            if (msg == null) {
078                return onMismatch;
079            }
080            final Matcher m = pattern.matcher(msg);
081            return m.matches() ? onMatch : onMismatch;
082        }
083    
084        @Override
085        public String toString() {
086            final StringBuilder sb = new StringBuilder();
087            sb.append("useRaw=").append(useRawMessage);
088            sb.append(", pattern=").append(pattern.toString());
089            return sb.toString();
090        }
091    
092        /**
093         * Create a Filter that matches a regular expression.
094         * @param regex The regular expression to match.
095         * @param useRawMsg If true, the raw message will be used, otherwise the formatted message will be used.
096         * @param match The action to perform when a match occurs.
097         * @param mismatch The action to perform when a mismatch occurs.
098         * @return The RegexFilter.
099         */
100        @PluginFactory
101        public static RegexFilter createFilter(@PluginAttr("regex") final String regex,
102                                               @PluginAttr("useRawMsg") final String useRawMsg,
103                                                @PluginAttr("onMatch") final String match,
104                                                @PluginAttr("onMismatch") final String mismatch) {
105    
106            if (regex == null) {
107                LOGGER.error("A regular expression must be provided for RegexFilter");
108                return null;
109            }
110            final boolean raw = useRawMsg == null ? false : Boolean.parseBoolean(useRawMsg);
111            Pattern pattern;
112            try {
113                pattern = Pattern.compile(regex);
114            } catch (final Exception ex) {
115                LOGGER.error("RegexFilter caught exception compiling pattern: " + regex + " cause: " + ex.getMessage());
116                return null;
117            }
118            final Result onMatch = Result.toResult(match);
119            final Result onMismatch = Result.toResult(mismatch);
120    
121            return new RegexFilter(raw, pattern, onMatch, onMismatch);
122        }
123    
124    }