You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@logging.apache.org by gg...@apache.org on 2016/12/14 18:13:24 UTC

logging-log4j2 git commit: [LOG4J2-1739]

Repository: logging-log4j2
Updated Branches:
  refs/heads/master cccf1ac97 -> d9b46929c


[LOG4J2-1739]

Add Builder to KafkaAppender and deprecate
KafkaAppender.createAppender(Layout, Filter, String, boolean, String,
Property[], Configuration).

Project: http://git-wip-us.apache.org/repos/asf/logging-log4j2/repo
Commit: http://git-wip-us.apache.org/repos/asf/logging-log4j2/commit/d9b46929
Tree: http://git-wip-us.apache.org/repos/asf/logging-log4j2/tree/d9b46929
Diff: http://git-wip-us.apache.org/repos/asf/logging-log4j2/diff/d9b46929

Branch: refs/heads/master
Commit: d9b46929c895216aa967be79e2bd2ba91c851154
Parents: cccf1ac
Author: Gary Gregory <gg...@apache.org>
Authored: Wed Dec 14 10:13:22 2016 -0800
Committer: Gary Gregory <gg...@apache.org>
Committed: Wed Dec 14 10:13:22 2016 -0800

----------------------------------------------------------------------
 .../core/appender/mom/kafka/KafkaAppender.java  | 290 +++++++++++--------
 .../core/appender/mom/kafka/KafkaManager.java   | 203 ++++++-------
 src/changes/changes.xml                         |   3 +
 3 files changed, 275 insertions(+), 221 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/d9b46929/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/mom/kafka/KafkaAppender.java
----------------------------------------------------------------------
diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/mom/kafka/KafkaAppender.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/mom/kafka/KafkaAppender.java
index 787f655..8029cf2 100644
--- a/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/mom/kafka/KafkaAppender.java
+++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/mom/kafka/KafkaAppender.java
@@ -1,120 +1,170 @@
-/*
- * 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.log4j.core.appender.mom.kafka;
-
-import java.io.Serializable;
-import java.nio.charset.StandardCharsets;
-import java.util.concurrent.TimeUnit;
-
-import org.apache.logging.log4j.core.Appender;
-import org.apache.logging.log4j.core.Filter;
-import org.apache.logging.log4j.core.Layout;
-import org.apache.logging.log4j.core.LogEvent;
-import org.apache.logging.log4j.core.appender.AbstractAppender;
-import org.apache.logging.log4j.core.appender.AppenderLoggingException;
-import org.apache.logging.log4j.core.config.Configuration;
-import org.apache.logging.log4j.core.config.Node;
-import org.apache.logging.log4j.core.config.Property;
-import org.apache.logging.log4j.core.config.plugins.Plugin;
-import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
-import org.apache.logging.log4j.core.config.plugins.PluginConfiguration;
-import org.apache.logging.log4j.core.config.plugins.PluginElement;
-import org.apache.logging.log4j.core.config.plugins.PluginFactory;
-import org.apache.logging.log4j.core.config.plugins.validation.constraints.Required;
-import org.apache.logging.log4j.core.layout.SerializedLayout;
-import org.apache.logging.log4j.core.util.StringEncoder;
-
-/**
- * Sends log events to an Apache Kafka topic.
- */
-@Plugin(name = "Kafka", category = Node.CATEGORY, elementType = Appender.ELEMENT_TYPE, printObject = true)
-public final class KafkaAppender extends AbstractAppender {
-
-    @PluginFactory
-    public static KafkaAppender createAppender(
-            @PluginElement("Layout") final Layout<? extends Serializable> layout,
-            @PluginElement("Filter") final Filter filter,
-            @Required(message = "No name provided for KafkaAppender") @PluginAttribute("name") final String name,
-            @PluginAttribute(value = "ignoreExceptions", defaultBoolean = true) final boolean ignoreExceptions,
-            @Required(message = "No topic provided for KafkaAppender") @PluginAttribute("topic") final String topic,
-            @PluginElement("Properties") final Property[] properties,
-            @PluginConfiguration final Configuration configuration) {
-        final KafkaManager kafkaManager = new KafkaManager(configuration.getLoggerContext(), name, topic, properties);
-        return new KafkaAppender(name, layout, filter, ignoreExceptions, kafkaManager);
-    }
-
-    private final KafkaManager manager;
-
-    private KafkaAppender(final String name, final Layout<? extends Serializable> layout, final Filter filter, final boolean ignoreExceptions, final KafkaManager manager) {
-        super(name, filter, layout, ignoreExceptions);
-        this.manager = manager;
-    }
-
-    @Override
-    public void append(final LogEvent event) {
-        if (event.getLoggerName().startsWith("org.apache.kafka")) {
-            LOGGER.warn("Recursive logging from [{}] for appender [{}].", event.getLoggerName(), getName());
-        } else {
-            try {
-                final Layout<? extends Serializable> layout = getLayout();
-                byte[] data;
-                if (layout != null) {
-                    if (layout instanceof SerializedLayout) {
-                        final byte[] header = layout.getHeader();
-                        final byte[] body = layout.toByteArray(event);
-                        data = new byte[header.length + body.length];
-                        System.arraycopy(header, 0, data, 0, header.length);
-                        System.arraycopy(body, 0, data, header.length, body.length);
-                    } else {
-                        data = layout.toByteArray(event);
-                    }
-                } else {
-                    data = StringEncoder.toBytes(event.getMessage().getFormattedMessage(), StandardCharsets.UTF_8);
-                }
-                manager.send(data);
-            } catch (final Exception e) {
-                LOGGER.error("Unable to write to Kafka [{}] for appender [{}].", manager.getName(), getName(), e);
-                throw new AppenderLoggingException("Unable to write to Kafka in appender: " + e.getMessage(), e);
-            }
-        }
-    }
-
-    @Override
-    public void start() {
-        super.start();
-        manager.startup();
-    }
-
-    @Override
-    public boolean stop(final long timeout, final TimeUnit timeUnit) {
-        setStopping();
-        boolean stopped = super.stop(timeout, timeUnit, false);
-        stopped &= manager.stop(timeout, timeUnit);
-        setStopped();
-        return stopped;
-    }
-
-    @Override
-    public String toString() {
-        return "KafkaAppender{" +
-            "name=" + getName() +
-            ", state=" + getState() +
-            ", topic=" + manager.getTopic() +
-            '}';
-    }
-}
+/*
+ * 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.log4j.core.appender.mom.kafka;
+
+import java.io.Serializable;
+import java.nio.charset.StandardCharsets;
+import java.util.Objects;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.logging.log4j.core.Appender;
+import org.apache.logging.log4j.core.Filter;
+import org.apache.logging.log4j.core.Layout;
+import org.apache.logging.log4j.core.LogEvent;
+import org.apache.logging.log4j.core.appender.AbstractAppender;
+import org.apache.logging.log4j.core.appender.AppenderLoggingException;
+import org.apache.logging.log4j.core.config.Configuration;
+import org.apache.logging.log4j.core.config.Node;
+import org.apache.logging.log4j.core.config.Property;
+import org.apache.logging.log4j.core.config.plugins.Plugin;
+import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
+import org.apache.logging.log4j.core.config.plugins.PluginBuilderFactory;
+import org.apache.logging.log4j.core.config.plugins.PluginConfiguration;
+import org.apache.logging.log4j.core.config.plugins.PluginElement;
+import org.apache.logging.log4j.core.config.plugins.validation.constraints.Required;
+import org.apache.logging.log4j.core.layout.SerializedLayout;
+import org.apache.logging.log4j.core.util.StringEncoder;
+
+/**
+ * Sends log events to an Apache Kafka topic.
+ */
+@Plugin(name = "Kafka", category = Node.CATEGORY, elementType = Appender.ELEMENT_TYPE, printObject = true)
+public final class KafkaAppender extends AbstractAppender {
+
+    /**
+     * Builds KafkaAppender instances.
+     * @param <B> The type to build
+     */
+    public static class Builder<B extends Builder<B>> extends AbstractAppender.Builder<B>
+            implements org.apache.logging.log4j.core.util.Builder<KafkaAppender> {
+
+        @PluginAttribute("topic") 
+        private String topic;
+        
+        @PluginElement("Properties") 
+        private Property[] properties;
+
+        @SuppressWarnings("resource")
+        @Override
+        public KafkaAppender build() {
+            final KafkaManager kafkaManager = new KafkaManager(getConfiguration().getLoggerContext(), getName(), topic, properties);
+            return new KafkaAppender(getName(), getLayout(), getFilter(), isIgnoreExceptions(), kafkaManager);
+        }
+
+        public String getTopic() {
+            return topic;
+        }
+
+        public Property[] getProperties() {
+            return properties;
+        }
+
+        public B setTopic(String topic) {
+            this.topic = topic;
+            return asBuilder();
+        }
+
+        public B setProperties(Property[] properties) {
+            this.properties = properties;
+            return asBuilder();
+        }
+    }
+    
+    @Deprecated
+    public static KafkaAppender createAppender(
+            @PluginElement("Layout") final Layout<? extends Serializable> layout,
+            @PluginElement("Filter") final Filter filter,
+            @Required(message = "No name provided for KafkaAppender") @PluginAttribute("name") final String name,
+            @PluginAttribute(value = "ignoreExceptions", defaultBoolean = true) final boolean ignoreExceptions,
+            @Required(message = "No topic provided for KafkaAppender") @PluginAttribute("topic") final String topic,
+            @PluginElement("Properties") final Property[] properties,
+            @PluginConfiguration final Configuration configuration) {
+        final KafkaManager kafkaManager = new KafkaManager(configuration.getLoggerContext(), name, topic, properties);
+        return new KafkaAppender(name, layout, filter, ignoreExceptions, kafkaManager);
+    }
+
+    /**
+     * Creates a builder for a KafkaAppender.
+     * @return a builder for a KafkaAppender.
+     */
+    @PluginBuilderFactory
+    public static <B extends Builder<B>> B newBuilder() {
+        return new Builder<B>().asBuilder();
+    }
+
+    private final KafkaManager manager;
+
+    private KafkaAppender(final String name, final Layout<? extends Serializable> layout, final Filter filter,
+            final boolean ignoreExceptions, final KafkaManager manager) {
+        super(name, filter, layout, ignoreExceptions);
+        this.manager = Objects.requireNonNull(manager, "manager");
+    }
+
+    @Override
+    public void append(final LogEvent event) {
+        if (event.getLoggerName().startsWith("org.apache.kafka")) {
+            LOGGER.warn("Recursive logging from [{}] for appender [{}].", event.getLoggerName(), getName());
+        } else {
+            try {
+                final Layout<? extends Serializable> layout = getLayout();
+                byte[] data;
+                if (layout != null) {
+                    if (layout instanceof SerializedLayout) {
+                        final byte[] header = layout.getHeader();
+                        final byte[] body = layout.toByteArray(event);
+                        data = new byte[header.length + body.length];
+                        System.arraycopy(header, 0, data, 0, header.length);
+                        System.arraycopy(body, 0, data, header.length, body.length);
+                    } else {
+                        data = layout.toByteArray(event);
+                    }
+                } else {
+                    data = StringEncoder.toBytes(event.getMessage().getFormattedMessage(), StandardCharsets.UTF_8);
+                }
+                manager.send(data);
+            } catch (final Exception e) {
+                LOGGER.error("Unable to write to Kafka [{}] for appender [{}].", manager.getName(), getName(), e);
+                throw new AppenderLoggingException("Unable to write to Kafka in appender: " + e.getMessage(), e);
+            }
+        }
+    }
+
+    @Override
+    public void start() {
+        super.start();
+        manager.startup();
+    }
+
+    @Override
+    public boolean stop(final long timeout, final TimeUnit timeUnit) {
+        setStopping();
+        boolean stopped = super.stop(timeout, timeUnit, false);
+        stopped &= manager.stop(timeout, timeUnit);
+        setStopped();
+        return stopped;
+    }
+
+    @Override
+    public String toString() {
+        return "KafkaAppender{" +
+            "name=" + getName() +
+            ", state=" + getState() +
+            ", topic=" + manager.getTopic() +
+            '}';
+    }
+}

http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/d9b46929/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/mom/kafka/KafkaManager.java
----------------------------------------------------------------------
diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/mom/kafka/KafkaManager.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/mom/kafka/KafkaManager.java
index ded641c..eb4d57b 100644
--- a/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/mom/kafka/KafkaManager.java
+++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/mom/kafka/KafkaManager.java
@@ -1,101 +1,102 @@
-/*
- * 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.log4j.core.appender.mom.kafka;
-
-import java.util.Properties;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
-
-import org.apache.kafka.clients.producer.Producer;
-import org.apache.kafka.clients.producer.ProducerRecord;
-import org.apache.logging.log4j.core.LoggerContext;
-import org.apache.logging.log4j.core.appender.AbstractManager;
-import org.apache.logging.log4j.core.config.Property;
-
-public class KafkaManager extends AbstractManager {
-
-    public static final String DEFAULT_TIMEOUT_MILLIS = "30000";
-
-    /**
-     * package-private access for testing.
-     */
-    static KafkaProducerFactory producerFactory = new DefaultKafkaProducerFactory();
-
-    private final Properties config = new Properties();
-    private Producer<byte[], byte[]> producer;
-    private final int timeoutMillis;
-
-    private final String topic;
-
-    public KafkaManager(final LoggerContext loggerContext, final String name, final String topic, final Property[] properties) {
-        super(loggerContext, name);
-        this.topic = topic;
-        config.setProperty("key.serializer", "org.apache.kafka.common.serialization.ByteArraySerializer");
-        config.setProperty("value.serializer", "org.apache.kafka.common.serialization.ByteArraySerializer");
-        config.setProperty("batch.size", "0");
-        for (final Property property : properties) {
-            config.setProperty(property.getName(), property.getValue());
-        }
-        this.timeoutMillis = Integer.parseInt(config.getProperty("timeout.ms", DEFAULT_TIMEOUT_MILLIS));
-    }
-
-    @Override
-    public boolean releaseSub(final long timeout, final TimeUnit timeUnit) {
-        if (timeout > 0) {
-            closeProducer(timeout, timeUnit);
-        } else {
-            closeProducer(timeoutMillis, TimeUnit.MILLISECONDS);
-        }
-        return true;
-    }
-
-    private void closeProducer(final long timeout, final TimeUnit timeUnit) {
-        if (producer != null) {
-            // This thread is a workaround for this Kafka issue: https://issues.apache.org/jira/browse/KAFKA-1660
-            final Runnable task = new Runnable() {
-                @Override
-                public void run() {
-                    if (producer != null) {
-                        producer.close();
-                    }
-                }
-            };
-            try {
-                getLoggerContext().submitDaemon(task).get(timeout, timeUnit);
-            } catch (InterruptedException | ExecutionException | TimeoutException e) {
-                // ignore
-            }
-        }
-    }
-
-    public void send(final byte[] msg) throws ExecutionException, InterruptedException, TimeoutException {
-        if (producer != null) {
-            producer.send(new ProducerRecord<byte[], byte[]>(topic, msg)).get(timeoutMillis, TimeUnit.MILLISECONDS);
-        }
-    }
-
-    public void startup() {
-        producer = producerFactory.newKafkaProducer(config);
-    }
-
-    public String getTopic() {
-        return topic;
-    }
-
-}
+/*
+ * 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.log4j.core.appender.mom.kafka;
+
+import java.util.Objects;
+import java.util.Properties;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+import org.apache.kafka.clients.producer.Producer;
+import org.apache.kafka.clients.producer.ProducerRecord;
+import org.apache.logging.log4j.core.LoggerContext;
+import org.apache.logging.log4j.core.appender.AbstractManager;
+import org.apache.logging.log4j.core.config.Property;
+
+public class KafkaManager extends AbstractManager {
+
+    public static final String DEFAULT_TIMEOUT_MILLIS = "30000";
+
+    /**
+     * package-private access for testing.
+     */
+    static KafkaProducerFactory producerFactory = new DefaultKafkaProducerFactory();
+
+    private final Properties config = new Properties();
+    private Producer<byte[], byte[]> producer;
+    private final int timeoutMillis;
+
+    private final String topic;
+
+    public KafkaManager(final LoggerContext loggerContext, final String name, final String topic, final Property[] properties) {
+        super(loggerContext, name);
+        this.topic = Objects.requireNonNull(topic, "topic");
+        config.setProperty("key.serializer", "org.apache.kafka.common.serialization.ByteArraySerializer");
+        config.setProperty("value.serializer", "org.apache.kafka.common.serialization.ByteArraySerializer");
+        config.setProperty("batch.size", "0");
+        for (final Property property : properties) {
+            config.setProperty(property.getName(), property.getValue());
+        }
+        this.timeoutMillis = Integer.parseInt(config.getProperty("timeout.ms", DEFAULT_TIMEOUT_MILLIS));
+    }
+
+    @Override
+    public boolean releaseSub(final long timeout, final TimeUnit timeUnit) {
+        if (timeout > 0) {
+            closeProducer(timeout, timeUnit);
+        } else {
+            closeProducer(timeoutMillis, TimeUnit.MILLISECONDS);
+        }
+        return true;
+    }
+
+    private void closeProducer(final long timeout, final TimeUnit timeUnit) {
+        if (producer != null) {
+            // This thread is a workaround for this Kafka issue: https://issues.apache.org/jira/browse/KAFKA-1660
+            final Runnable task = new Runnable() {
+                @Override
+                public void run() {
+                    if (producer != null) {
+                        producer.close();
+                    }
+                }
+            };
+            try {
+                getLoggerContext().submitDaemon(task).get(timeout, timeUnit);
+            } catch (InterruptedException | ExecutionException | TimeoutException e) {
+                // ignore
+            }
+        }
+    }
+
+    public void send(final byte[] msg) throws ExecutionException, InterruptedException, TimeoutException {
+        if (producer != null) {
+            producer.send(new ProducerRecord<byte[], byte[]>(topic, msg)).get(timeoutMillis, TimeUnit.MILLISECONDS);
+        }
+    }
+
+    public void startup() {
+        producer = producerFactory.newKafkaProducer(config);
+    }
+
+    public String getTopic() {
+        return topic;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/d9b46929/src/changes/changes.xml
----------------------------------------------------------------------
diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index 17fd5a0..a2784ff 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -237,6 +237,9 @@
       <action issue="LOG4J2-1738" dev="ggregory" type="add">
         Add a Builder to JsonLayout and deprecate org.apache.logging.log4j.core.layout.JsonLayout.createLayout(Configuration, boolean, boolean, boolean, boolean, boolean, boolean, String, String, Charset, boolean).
       </action>
+      <action issue="LOG4J2-1739" dev="ggregory" type="add">
+        Add Builder to KafkaAppender and deprecate KafkaAppender.createAppender(Layout, Filter, String, boolean, String, Property[], Configuration).
+      </action>
     </release>
     <release version="2.7" date="2016-10-02" description="GA Release 2.7">
       <action issue="LOG4J2-1618" dev="rpopma" type="fix" due-to="Raman Gupta">