log4j2 property 配置问题

由于要把logback框架升级到log4j2,把配置改了一遍。发现property属性总是配置失败。跟踪了代码,发现log4j2的小伙砸写的代码有问题。但不知道其他人的配置为什么能工作。

logback配置

<property name="LICAI_LOG_HOME" value="/data/logs/tomcat/licaiweb" />

先上正确的log4j2配置

<Properties>
    <Property name="LICAI_LOG_HOME">
    <![CDATA[/data/logs/tomcat/licaiweb]]>
        </Property>
</Properties>

 跟踪代码发现了问题。

private void constructHierarchy(final Node node, final Element element) {
        processAttributes(node, element);
        final StringBuilder buffer = new StringBuilder();
        final NodeList list = element.getChildNodes();
        final List<Node> children = node.getChildren();
        for (int i = 0; i < list.getLength(); i++) {
            final org.w3c.dom.Node w3cNode = list.item(i);
            if (w3cNode instanceof Element) {
                final Element child = (Element) w3cNode;
                final String name = getType(child);
                final PluginType<?> type = pluginManager.getPluginType(name);
                final Node childNode = new Node(node, name, type);
                constructHierarchy(childNode, child);
                if (type == null) {
                    final String value = childNode.getValue();
                    if (!childNode.hasChildren() && value != null) {
                        node.getAttributes().put(name, value);
                    } else {
                        status.add(new Status(name, element, ErrorType.CLASS_NOT_FOUND));
                    }
                } else {
                    children.add(childNode);
                }
            } else if (w3cNode instanceof Text) {
                final Text data = (Text) w3cNode;
                buffer.append(data.getData());
            }
        }

//property没有子元素的时候,value="",非null
        final String text = buffer.toString().trim();
        if (text.length() > 0 || (!node.hasChildren() && !node.isRoot())) {
            node.setValue(text);
        }
    }
public class PluginValueVisitor extends AbstractPluginVisitor<PluginValue> {
    public PluginValueVisitor() {
        super(PluginValue.class);
    }

    @Override
    public Object visit(final Configuration configuration, final Node node, final LogEvent event,
                        final StringBuilder log) {
        final String name = this.annotation.value();
//发现value非null,就返回原来的value了,即""
        final String rawValue = node.getValue() != null ? node.getValue() :
            removeAttributeValue(node.getAttributes(), "value");
        final String value = this.substitutor.replace(event, rawValue);
        StringBuilders.appendKeyDqValue(log, name, value);
        return value;
    }
}

猜你喜欢

转载自tianzhihehe.iteye.com/blog/2280387