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.regex.Matcher;
020import java.util.regex.Pattern;
021
022import org.apache.logging.log4j.Level;
023import org.apache.logging.log4j.Marker;
024import org.apache.logging.log4j.core.LogEvent;
025import org.apache.logging.log4j.core.Logger;
026import org.apache.logging.log4j.core.config.plugins.Plugin;
027import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
028import org.apache.logging.log4j.core.config.plugins.PluginFactory;
029import org.apache.logging.log4j.message.Message;
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)
040public 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(
108            @PluginAttribute("regex") final String regex,
109            @PluginAttribute("useRawMsg") final String useRawMsg,
110            @PluginAttribute("onMatch") final String match,
111            @PluginAttribute("onMismatch") final String mismatch) {
112
113        if (regex == null) {
114            LOGGER.error("A regular expression must be provided for RegexFilter");
115            return null;
116        }
117        final boolean raw = Boolean.parseBoolean(useRawMsg);
118        Pattern pattern;
119        try {
120            pattern = Pattern.compile(regex);
121        } catch (final Exception ex) {
122            LOGGER.error("RegexFilter caught exception compiling pattern: " + regex + " cause: " + ex.getMessage());
123            return null;
124        }
125        final Result onMatch = Result.toResult(match);
126        final Result onMismatch = Result.toResult(mismatch);
127
128        return new RegexFilter(raw, pattern, onMatch, onMismatch);
129    }
130
131}