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.pattern;
018
019 import java.util.regex.Pattern;
020
021 import org.apache.logging.log4j.Logger;
022 import org.apache.logging.log4j.core.config.plugins.Plugin;
023 import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
024 import org.apache.logging.log4j.core.config.plugins.PluginFactory;
025 import org.apache.logging.log4j.status.StatusLogger;
026
027 /**
028 * Replace tokens in the LogEvent message.
029 */
030 @Plugin(name = "replace", category = "Core", printObject = true)
031 public final class RegexReplacement {
032
033 private static final Logger LOGGER = StatusLogger.getLogger();
034
035 private final Pattern pattern;
036
037 private final String substitution;
038
039 /**
040 * Private constructor.
041 *
042 * @param pattern The Pattern.
043 * @param substitution The substitution String.
044 */
045 private RegexReplacement(final Pattern pattern, final String substitution) {
046 this.pattern = pattern;
047 this.substitution = substitution;
048 }
049
050 /**
051 * Perform the replacement.
052 * @param msg The String to match against.
053 * @return the replacement String.
054 */
055 public String format(final String msg) {
056 return pattern.matcher(msg).replaceAll(substitution);
057 }
058
059 @Override
060 public String toString() {
061 return "replace(regex=" + pattern.pattern() + ", replacement=" + substitution + ')';
062 }
063
064 /**
065 * Create a RegexReplacement.
066 * @param regex The regular expression to locate.
067 * @param replacement The replacement value.
068 * @return A RegexReplacement.
069 */
070 @PluginFactory
071 public static RegexReplacement createRegexReplacement(
072 @PluginAttribute("regex") final Pattern regex,
073 @PluginAttribute("replacement") final String replacement) {
074 if (regex == null) {
075 LOGGER.error("A regular expression is required for replacement");
076 return null;
077 }
078 if (replacement == null) {
079 LOGGER.error("A replacement string is required to perform replacement");
080 }
081 // FIXME: should we use Matcher.quoteReplacement() here?
082 return new RegexReplacement(regex, replacement);
083 }
084
085 }