Skip to content

Commit

Permalink
Add support for Log4j 1 configuration formats (#145)
Browse files Browse the repository at this point in the history
This adds support for Log4j 1 configuration formats to the Configuration Converter API
Since Log4j Core 2 is a complete rewrite for Log4j 1, the converter:

- Needs to know exactly what configuration parameters a Log4j 1 component supports to create an equivalent Log4j Core 2 configuration.
- Introduces a pluggable `spi/v1/Log4j1ComponentParser` interface.
  For each supported Log4j 1 component, an implementation of this interface must be provided and registered with `ServiceLoader`.

The following Log4j 1 components are currently supported:

- Appenders: `ConsoleAppender`, `DailyRollingFileAppender`, `FileAppender` and `RollingFileAppender`.
- Filters: `DenyAllFilter`, `LevelMatchFilter`, `LevelRangeFilter` and `StringMatchFilter`.
- Layouts: `HTMLLayout`, `PatternLayout`, `SimpleLayout`, `TTCCLayout`.

Part of apache/logging-log4j2#3220
  • Loading branch information
ppkarwasz authored Nov 27, 2024
1 parent f4392b1 commit e0ccc53
Show file tree
Hide file tree
Showing 47 changed files with 3,910 additions and 64 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -33,17 +33,24 @@ public static ConfigurationNodeBuilder newNodeBuilder() {
return new ConfigurationNodeBuilder();
}

public static ConfigurationNode createThresholdFilter(String level) {
public static ConfigurationNode newAppenderRef(String ref) {
return newNodeBuilder()
.setPluginName("AppenderRef")
.addAttribute("ref", ref)
.get();
}

public static ConfigurationNode newThresholdFilter(String level) {
return newNodeBuilder()
.setPluginName("ThresholdFilter")
.addAttribute("level", level)
.build();
.get();
}

public static ConfigurationNode createCompositeFilter(Iterable<? extends ConfigurationNode> filters) {
public static ConfigurationNode newCompositeFilter(Iterable<? extends ConfigurationNode> filters) {
ConfigurationNodeBuilder builder = newNodeBuilder().setPluginName("Filters");
filters.forEach(builder::addChild);
return builder.build();
return builder.get();
}

private ComponentUtils() {}
Expand Down Expand Up @@ -73,22 +80,23 @@ public ConfigurationNodeBuilder addAttribute(String key, boolean value) {
return this;
}

public ConfigurationNodeBuilder addAttribute(String key, int value) {
attributes.put(key, String.valueOf(value));
return this;
}

public ConfigurationNodeBuilder addChild(ConfigurationNode child) {
children.add(child);
return this;
}

public ConfigurationNode build() {
@Override
public ConfigurationNode get() {
if (pluginName == null) {
throw new ConfigurationConverterException("No plugin name specified");
}
return new ConfigurationNodeImpl(pluginName, attributes, children);
}

@Override
public ConfigurationNode get() {
return build();
}
}

private static final class ConfigurationNodeImpl implements ConfigurationNode {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to you under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.logging.converter.config.internal;

import java.util.Map;
import java.util.Properties;
import java.util.stream.Stream;
import org.apache.logging.converter.config.ConfigurationConverterException;
import org.apache.logging.converter.config.spi.v1.PropertiesSubset;
import org.jspecify.annotations.Nullable;

public final class PropertiesUtils {

public static @Nullable String getAndRemove(Properties properties, String key) {
return (String) properties.remove(key);
}

public static String getLastComponent(String name) {
int idx = name.lastIndexOf('.');
return idx == -1 ? name : name.substring(idx + 1);
}

public static Properties extractSubset(Properties properties, String prefix) {
Properties subset = org.apache.logging.log4j.util.PropertiesUtil.extractSubset(properties, prefix);
String value = getAndRemove(properties, prefix);
if (value != null) {
subset.setProperty("", value);
}
return subset;
}

public static @Nullable String extractProperty(PropertiesSubset subset, String key) {
return (String) subset.getProperties().remove(key);
}

public static PropertiesSubset extractSubset(PropertiesSubset parentSubset, String childPrefix) {
Properties parentProperties = parentSubset.getProperties();
Properties properties =
org.apache.logging.log4j.util.PropertiesUtil.extractSubset(parentProperties, childPrefix);
String value = getAndRemove(parentProperties, childPrefix);
if (value != null) {
properties.setProperty("", value);
}
return PropertiesSubset.of(addPrefixes(parentSubset.getPrefix(), childPrefix), properties);
}

public static Map<String, Properties> partitionOnCommonPrefixes(Properties properties) {
return org.apache.logging.log4j.util.PropertiesUtil.partitionOnCommonPrefixes(properties, true);
}

public static Stream<PropertiesSubset> partitionOnCommonPrefixes(PropertiesSubset parentSubset) {
String parentPrefix = parentSubset.getPrefix();
String effectivePrefix = parentPrefix.isEmpty() ? parentPrefix : parentPrefix + ".";
return org.apache.logging.log4j.util.PropertiesUtil.partitionOnCommonPrefixes(
parentSubset.getProperties(), true)
.entrySet()
.stream()
.map(entry -> PropertiesSubset.of(effectivePrefix + entry.getKey(), entry.getValue()));
}

private static String addPrefixes(String left, String right) {
return left.isEmpty() ? right : right.isEmpty() ? left : left + "." + right;
}

public static void throwIfNotEmpty(PropertiesSubset subset) {
Properties properties = subset.getProperties();
if (!properties.isEmpty()) {
String prefix = subset.getPrefix();
if (properties.size() == 1) {
throw new ConfigurationConverterException("Unknown configuration property '"
+ addPrefixes(
prefix,
properties.stringPropertyNames().iterator().next()) + "'.");
}
StringBuilder messageBuilder = new StringBuilder("Unknown configuration properties:");
properties.stringPropertyNames().stream()
.map(k -> addPrefixes(prefix, k))
.forEach(k -> messageBuilder.append("\n\t").append(k));
throw new ConfigurationConverterException(messageBuilder.toString());
}
}

private PropertiesUtils() {}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to you under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.logging.converter.config.internal;

import java.util.regex.Pattern;
import org.apache.logging.converter.config.ConfigurationConverterException;
import org.apache.logging.log4j.util.Strings;

public final class StringUtils {

private static final Pattern SUBSTITUTION_PATTERN = Pattern.compile("\\$\\{([^}]+)\\}");

public static final String FALSE = "false";
public static final String TRUE = "true";

public static String capitalize(String value) {
if (Strings.isEmpty(value) || Character.isUpperCase(value.charAt(0))) {
return value;
}
final char[] chars = value.toCharArray();
chars[0] = Character.toUpperCase(chars[0]);
return new String(chars);
}

public static String decapitalize(String value) {
if (Strings.isEmpty(value) || Character.isLowerCase(value.charAt(0))) {
return value;
}
final char[] chars = value.toCharArray();
chars[0] = Character.toLowerCase(chars[0]);
return new String(chars);
}

public static boolean parseBoolean(String value) {
return Boolean.parseBoolean(value.trim());
}

public static int parseInteger(String value) {
try {
return Integer.parseInt(value.trim());
} catch (NumberFormatException e) {
throw new ConfigurationConverterException("Invalid integer value: " + value, e);
}
}

public static long parseLong(String value) {
try {
return Long.parseLong(value.trim());
} catch (NumberFormatException e) {
throw new ConfigurationConverterException("Invalid long value: " + value, e);
}
}

public static String convertPropertySubstitution(String value) {
return SUBSTITUTION_PATTERN.matcher(value).replaceAll("${sys:$1}");
}

private StringUtils() {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.logging.converter.config.ConfigurationConverterException;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
Expand Down Expand Up @@ -60,6 +61,41 @@ public static DocumentBuilder createDocumentBuilderV2() throws IOException {
return newDocumentBuilder(factory);
}

/**
* Finds an XPath expression that helps to identify a node in an XML document
*
* @param node An XML node.
* @return An XPath expression.
*/
public static String getXPathExpression(Element node) {
String tagName = node.getTagName();
// Position of the node among siblings
int position = 1;
Node sibling = node.getPreviousSibling();
while (sibling != null) {
if (sibling instanceof Element && tagName.equals(((Element) sibling).getTagName())) {
position++;
}
sibling = sibling.getPreviousSibling();
}
Node parent = node.getParentNode();
String parentExpression = parent instanceof Element ? getXPathExpression((Element) parent) : "";
return parentExpression + "/" + tagName + "[" + position + "]";
}

public static void throwUnknownElement(Element node) {
throw new ConfigurationConverterException("Unknown configuration element '" + getXPathExpression(node) + "'.");
}

public static String requireNonEmpty(Element node, String attributeName) {
String value = node.getAttribute(attributeName);
if (value.isEmpty()) {
throw new ConfigurationConverterException("Missing required attribute '" + attributeName
+ "' on configuration element '" + getXPathExpression(node) + "'.");
}
return value;
}

private static void disableXIncludeAware(DocumentBuilderFactory factory) throws IOException {
try {
factory.setXIncludeAware(false);
Expand Down
Loading

0 comments on commit e0ccc53

Please sign in to comment.