You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pulsar.apache.org by lh...@apache.org on 2026/10/20 21:41:16 UTC

(pulsar) 02/05: [improve][broker] Enable Log4j2 async loggers again (#26979)

This is an automated email from the ASF dual-hosted git repository.

lhotari pushed a commit to branch branch-5.0
in repository https://gitbox.apache.org/repos/asf/pulsar.git

commit ee9a0acd6f50a45f6fdc52d587dc3c0fe23b4c77
Author: Matteo Merli <mm...@apache.org>
AuthorDate: Tue Oct 20 09:33:27 2026 -0700

    [improve][broker] Enable Log4j2 async loggers again (#26979)
    
    (cherry picked from commit 69683f49981e2abe7350c3b85d82566c9c719cdb)
---
 bin/pulsar                                         |   6 +
 distribution/server/build.gradle.kts               |   2 +
 gradle/libs.versions.toml                          |   4 +-
 pulsar-functions/instance/build.gradle.kts         |   2 +
 .../functions/instance/JavaInstanceRunnable.java   |  25 ++-
 .../pulsar/functions/instance/LogAppender.java     |  62 +++++++
 .../pulsar/functions/instance/LogAppenderTest.java | 202 +++++++++++++++++++++
 7 files changed, 296 insertions(+), 7 deletions(-)

diff --git a/bin/pulsar b/bin/pulsar
index d7513c654247..9ca60ec9b8d9 100755
--- a/bin/pulsar
+++ b/bin/pulsar
@@ -339,6 +339,12 @@ OPTS="-cp $PULSAR_CLASSPATH $OPTS"
 # -Dio.netty.leakDetection.level=simple in PULSAR_EXTRA_OPTS (BOOKIE_EXTRA_OPTS for bookies), override this.
 OPTS="-Dio.netty.leakDetection.level=disabled $OPTS"
 
+# Log4j2 async loggers: the threads that log hand their events to a background thread instead of writing them, so
+# that writing the logs doesn't stall them, see https://logging.apache.org/log4j/2.x/manual/async.html.
+# To log synchronously, set -Dlog4j2.contextSelector=org.apache.logging.log4j.core.selector.ClassLoaderContextSelector
+# in PULSAR_EXTRA_OPTS (BOOKIE_EXTRA_OPTS for bookies), which come later on the command line and override this.
+OPTS="-Dlog4j2.contextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector $OPTS"
+
 if [ $COMMAND == "bookie" ]; then
   # Pass BOOKIE_EXTRA_OPTS option defined in bkenv.sh
   OPTS="$OPTS $BOOKIE_MEM $BOOKIE_GC $BOOKIE_GC_LOG $BOOKIE_EXTRA_OPTS"
diff --git a/distribution/server/build.gradle.kts b/distribution/server/build.gradle.kts
index 944ac719bcae..4b19c700721c 100644
--- a/distribution/server/build.gradle.kts
+++ b/distribution/server/build.gradle.kts
@@ -125,6 +125,8 @@ dependencies {
     distLib(libs.log4j.layout.template.json)
     distLib(libs.log4j.slf4j2.impl)
     distLib(libs.log4j.jul)
+    // The async loggers that bin/pulsar enables need the LMAX Disruptor
+    distLib(libs.disruptor)
     distLib(libs.simpleclient.log4j2)
 
     // Metrics
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml
index 5fd19728518c..1dfee261c453 100644
--- a/gradle/libs.versions.toml
+++ b/gradle/libs.versions.toml
@@ -144,7 +144,8 @@ netty-reactive-streams = "2.0.20"
 # 9.2.0+ is required for CronType.SPRING53 (Spring 5.3+ cron syntax)
 cron-utils = "9.2.1"
 failsafe = "3.3.2"
-disruptor = "3.4.3"
+# The LMAX Disruptor of log4j2's async loggers, which bin/pulsar enables
+disruptor = "4.0.0"
 ant = "1.10.17"
 # guice is held at 5.1.0 to match what TestNG 7.x declares; Guice 7 switches from
 # javax.inject to jakarta.inject. jclouds is the only consumer that needs Guice 7 and
@@ -229,6 +230,7 @@ log4j-web = { module = "org.apache.logging.log4j:log4j-web", version.ref = "log4
 log4j-layout-template-json = { module = "org.apache.logging.log4j:log4j-layout-template-json", version.ref = "log4j2" }
 log4j-slf4j2-impl = { module = "org.apache.logging.log4j:log4j-slf4j2-impl", version.ref = "log4j2" }
 log4j-jul = { module = "org.apache.logging.log4j:log4j-jul", version.ref = "log4j2" }
+disruptor = { module = "com.lmax:disruptor", version.ref = "disruptor" }
 # slog
 slog = { module = "io.github.merlimat.slog:slog", version.ref = "slog" }
 # Lombok
diff --git a/pulsar-functions/instance/build.gradle.kts b/pulsar-functions/instance/build.gradle.kts
index e099acbf0d69..ece2e73b4ee2 100644
--- a/pulsar-functions/instance/build.gradle.kts
+++ b/pulsar-functions/instance/build.gradle.kts
@@ -69,6 +69,8 @@ dependencies {
     // Main code only touches com.google.protobuf reflectively (protobuf schema detection for user
     // functions); tests exercise that path with concrete protobuf types.
     testImplementation(libs.protobuf.java)
+    // Log4j2's async loggers, which the broker and the functions worker use, for the log topic appender's tests
+    testImplementation(libs.disruptor)
 }
 
 tasks.withType<Test> {
diff --git a/pulsar-functions/instance/src/main/java/org/apache/pulsar/functions/instance/JavaInstanceRunnable.java b/pulsar-functions/instance/src/main/java/org/apache/pulsar/functions/instance/JavaInstanceRunnable.java
index 7506e0ffd5b0..ec5a848e7bca 100644
--- a/pulsar-functions/instance/src/main/java/org/apache/pulsar/functions/instance/JavaInstanceRunnable.java
+++ b/pulsar-functions/instance/src/main/java/org/apache/pulsar/functions/instance/JavaInstanceRunnable.java
@@ -128,6 +128,9 @@ import org.slf4j.LoggerFactory;
 @CustomLog
 public class JavaInstanceRunnable implements AutoCloseable, Runnable {
 
+    // How long the close waits for the log topic's appender to receive the events logged before it
+    private static final long LOG_TOPIC_DRAIN_TIMEOUT_MS = 5000;
+
     private final InstanceConfig instanceConfig;
 
     // input topic consumer & output topic producer
@@ -715,8 +718,8 @@ public class JavaInstanceRunnable implements AutoCloseable, Runnable {
         producerCache.close();
 
         if (logAppender != null) {
-            removeLogTopicAppender(LoggerContext.getContext());
-            removeLogTopicAppender(LoggerContext.getContext(false));
+            removeLogTopicAppender(LoggerContext.getContext(), logAppender);
+            removeLogTopicAppender(LoggerContext.getContext(false), logAppender);
             logAppender.stop();
             logAppender = null;
         }
@@ -860,12 +863,13 @@ public class JavaInstanceRunnable implements AutoCloseable, Runnable {
                     ? new LogAppender(clientV5, logTopic, fqn, instanceConfig.getInstanceName())
                     : new LogAppender(client, logTopic, fqn, instanceConfig.getInstanceName());
             logAppender.start();
-            setupLogTopicAppender(LoggerContext.getContext());
-            setupLogTopicAppender(LoggerContext.getContext(false));
+            setupLogTopicAppender(LoggerContext.getContext(), logAppender);
+            setupLogTopicAppender(LoggerContext.getContext(false), logAppender);
         }
     }
 
-    private void setupLogTopicAppender(LoggerContext context) {
+    @VisibleForTesting
+    static void setupLogTopicAppender(LoggerContext context, LogAppender logAppender) {
         Configuration config = context.getConfiguration();
         config.addAppender(logAppender);
         for (final LoggerConfig loggerConfig : config.getLoggers().values()) {
@@ -875,7 +879,16 @@ public class JavaInstanceRunnable implements AutoCloseable, Runnable {
         context.updateLoggers();
     }
 
-    private void removeLogTopicAppender(LoggerContext context) {
+    @VisibleForTesting
+    static void removeLogTopicAppender(LoggerContext context, LogAppender logAppender) {
+        // With async loggers, the events logged before the close may still be queued: let them reach the log topic
+        // before the loggers stop handing events to the appender
+        if (!logAppender.drain(context, LOG_TOPIC_DRAIN_TIMEOUT_MS)) {
+            log.warn()
+                    .attr("function", logAppender.getName())
+                    .attr("timeoutMs", LOG_TOPIC_DRAIN_TIMEOUT_MS)
+                    .log("Removing the log topic appender before it received every event logged before the close");
+        }
         Configuration config = context.getConfiguration();
         for (final LoggerConfig loggerConfig : config.getLoggers().values()) {
             loggerConfig.removeAppender(logAppender.getName());
diff --git a/pulsar-functions/instance/src/main/java/org/apache/pulsar/functions/instance/LogAppender.java b/pulsar-functions/instance/src/main/java/org/apache/pulsar/functions/instance/LogAppender.java
index 673389246ea9..a263843383d3 100644
--- a/pulsar-functions/instance/src/main/java/org/apache/pulsar/functions/instance/LogAppender.java
+++ b/pulsar-functions/instance/src/main/java/org/apache/pulsar/functions/instance/LogAppender.java
@@ -21,13 +21,25 @@ package org.apache.pulsar.functions.instance;
 import java.io.Serializable;
 import java.nio.charset.StandardCharsets;
 import java.time.Duration;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutionException;
 import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
 import java.util.function.Supplier;
+import org.apache.logging.log4j.Level;
+import org.apache.logging.log4j.Marker;
+import org.apache.logging.log4j.MarkerManager;
 import org.apache.logging.log4j.core.Appender;
 import org.apache.logging.log4j.core.ErrorHandler;
 import org.apache.logging.log4j.core.Layout;
 import org.apache.logging.log4j.core.LogEvent;
+import org.apache.logging.log4j.core.LoggerContext;
 import org.apache.logging.log4j.core.appender.DefaultErrorHandler;
+import org.apache.logging.log4j.core.config.Configuration;
+import org.apache.logging.log4j.core.config.LoggerConfig;
 import org.apache.pulsar.client.api.CompressionType;
 import org.apache.pulsar.client.api.Producer;
 import org.apache.pulsar.client.api.PulsarClient;
@@ -46,6 +58,8 @@ public class LogAppender implements Appender {
     private static final String LOG_LEVEL = "loglevel";
     private static final String INSTANCE = "instance";
     private static final String FQN = "fqn";
+    // The marker of the events that drain() logs, which end its wait instead of going to the log topic
+    private static final Marker DRAIN_MARKER = MarkerManager.getMarker("PULSAR_FUNCTION_LOG_TOPIC_DRAIN");
 
     private PulsarClient pulsarClient;
     private Supplier<org.apache.pulsar.client.api.v5.PulsarClient> pulsarClientV5;
@@ -55,6 +69,8 @@ public class LogAppender implements Appender {
     private State state;
     private ErrorHandler errorHandler;
     private Producer<byte[]> producer;
+    // The waits of drain(), by the message of the event that each one waits for
+    private final Map<String, CompletableFuture<Void>> drains = new ConcurrentHashMap<>();
 
     public LogAppender(PulsarClient pulsarClient, String logTopic, String fqn, String instance) {
         this.pulsarClient = pulsarClient;
@@ -75,6 +91,13 @@ public class LogAppender implements Appender {
 
     @Override
     public void append(LogEvent logEvent) {
+        if (DRAIN_MARKER.equals(logEvent.getMarker())) {
+            CompletableFuture<Void> drained = drains.get(logEvent.getMessage().getFormattedMessage());
+            if (drained != null) {
+                drained.complete(null);
+            }
+            return;
+        }
         producer.newMessage()
                 .value(logEvent.getMessage().getFormattedMessage().getBytes(StandardCharsets.UTF_8))
                 .property(LOG_LEVEL, logEvent.getLevel().name())
@@ -83,6 +106,45 @@ public class LogAppender implements Appender {
                 .sendAsync();
     }
 
+    /**
+     * Waits until this appender has received the events that the context's loggers accepted before this call, for at
+     * most the timeout, and returns whether it did.
+     *
+     * <p>With async loggers, the context's background thread hands each event to the appenders attached when it gets
+     * to the event, so an event still queued when the appender is detached never reaches the log topic. The thread
+     * handles the events in order: this logs an event that only this appender receives, through a logger of its own,
+     * and waits for it. With synchronous loggers, the event arrives at once.
+     */
+    boolean drain(LoggerContext context, long timeoutMillis) {
+        String loggerName = LogAppender.class.getName() + ".drain." + fqn + "." + instance;
+        Configuration config = context.getConfiguration();
+        // The logger's configuration stays, without appenders, after the drain: an event that the background thread
+        // handles after the timeout must not reach the configuration's other appenders through the root logger
+        if (!config.getLoggers().containsKey(loggerName)) {
+            config.addLogger(loggerName, new LoggerConfig(loggerName, Level.ALL, false));
+        }
+        LoggerConfig loggerConfig = config.getLoggers().get(loggerName);
+        loggerConfig.addAppender(this, null, null);
+        context.updateLoggers();
+        String id = UUID.randomUUID().toString();
+        CompletableFuture<Void> drained = new CompletableFuture<>();
+        drains.put(id, drained);
+        try {
+            // At the most severe level, which a queue-full policy that discards events keeps
+            context.getLogger(loggerName).log(Level.FATAL, DRAIN_MARKER, id);
+            drained.get(timeoutMillis, TimeUnit.MILLISECONDS);
+            return true;
+        } catch (InterruptedException e) {
+            Thread.currentThread().interrupt();
+            return false;
+        } catch (ExecutionException | TimeoutException e) {
+            return false;
+        } finally {
+            drains.remove(id);
+            loggerConfig.removeAppender(getName());
+        }
+    }
+
     @Override
     public String getName() {
         return fqn;
diff --git a/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/instance/LogAppenderTest.java b/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/instance/LogAppenderTest.java
new file mode 100644
index 000000000000..fa2400124a4a
--- /dev/null
+++ b/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/instance/LogAppenderTest.java
@@ -0,0 +1,202 @@
+/*
+ * 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.pulsar.functions.instance;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.RETURNS_SELF;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertTrue;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import org.apache.logging.log4j.Level;
+import org.apache.logging.log4j.core.LogEvent;
+import org.apache.logging.log4j.core.Logger;
+import org.apache.logging.log4j.core.LoggerContext;
+import org.apache.logging.log4j.core.appender.AbstractAppender;
+import org.apache.logging.log4j.core.async.AsyncLoggerContext;
+import org.apache.logging.log4j.core.config.Configuration;
+import org.apache.logging.log4j.core.config.Property;
+import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilder;
+import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilderFactory;
+import org.apache.logging.log4j.core.config.builder.impl.BuiltConfiguration;
+import org.apache.pulsar.client.api.Producer;
+import org.apache.pulsar.client.api.ProducerBuilder;
+import org.apache.pulsar.client.api.PulsarClient;
+import org.apache.pulsar.client.api.TypedMessageBuilder;
+import org.awaitility.Awaitility;
+import org.testng.annotations.Test;
+
+/**
+ * The log topic's appender when a function instance closes: the events logged before the close reach the log topic,
+ * also when async loggers hand them to the appender after the close started.
+ */
+public class LogAppenderTest {
+
+    @Test
+    public void testEventsQueuedBeforeTheCloseReachTheLogTopic() throws Exception {
+        RecordingAppender recording = new RecordingAppender();
+        AsyncLoggerContext context = start(new AsyncLoggerContext("log-appender-async-test"), recording);
+        List<String> published = new CopyOnWriteArrayList<>();
+        try {
+            LogAppender logAppender = newLogAppender(published);
+            JavaInstanceRunnable.setupLogTopicAppender(context, logAppender);
+            Logger logger = context.getLogger("function");
+            // Hold the background thread on an earlier event, so that the last event waits in the queue
+            logger.info("block");
+            assertTrue(recording.blocked.await(10, TimeUnit.SECONDS));
+            logger.info("last");
+
+            Thread close = new Thread(() -> {
+                JavaInstanceRunnable.removeLogTopicAppender(context, logAppender);
+                logAppender.stop();
+            });
+            close.start();
+            // Release the background thread once the close waits for it, or has detached the appender without waiting
+            Awaitility.await().until(() -> close.getState() == Thread.State.TIMED_WAITING
+                    || close.getState() == Thread.State.TERMINATED);
+            recording.release.countDown();
+            close.join(TimeUnit.SECONDS.toMillis(10));
+
+            assertFalse(close.isAlive());
+            assertEquals(published, List.of("block", "last"));
+            assertDetached(context, logAppender);
+        } finally {
+            recording.release.countDown();
+            context.stop(10, TimeUnit.SECONDS);
+        }
+    }
+
+    @Test
+    public void testDrainWithSynchronousLoggers() throws Exception {
+        LoggerContext context = start(new LoggerContext("log-appender-sync-test"), new RecordingAppender());
+        List<String> published = new CopyOnWriteArrayList<>();
+        try {
+            LogAppender logAppender = newLogAppender(published);
+            JavaInstanceRunnable.setupLogTopicAppender(context, logAppender);
+            context.getLogger("function").info("last");
+
+            assertTrue(logAppender.drain(context, 0));
+            JavaInstanceRunnable.removeLogTopicAppender(context, logAppender);
+            logAppender.stop();
+
+            assertEquals(published, List.of("last"));
+            assertDetached(context, logAppender);
+        } finally {
+            context.stop(10, TimeUnit.SECONDS);
+        }
+    }
+
+    @Test
+    public void testDrainGivesUpAfterTheTimeout() throws Exception {
+        RecordingAppender recording = new RecordingAppender();
+        AsyncLoggerContext context = start(new AsyncLoggerContext("log-appender-timeout-test"), recording);
+        List<String> published = new CopyOnWriteArrayList<>();
+        try {
+            LogAppender logAppender = newLogAppender(published);
+            JavaInstanceRunnable.setupLogTopicAppender(context, logAppender);
+            Logger logger = context.getLogger("function");
+            logger.info("block");
+            assertTrue(recording.blocked.await(10, TimeUnit.SECONDS));
+
+            assertFalse(logAppender.drain(context, 100));
+
+            // The drain's event, which the background thread handles after the timeout, reaches no other appender
+            recording.release.countDown();
+            logger.info("after");
+            Awaitility.await().until(() -> recording.received.contains("after"));
+            assertEquals(recording.received, List.of("block", "after"));
+            assertEquals(published, List.of("block", "after"));
+        } finally {
+            recording.release.countDown();
+            context.stop(10, TimeUnit.SECONDS);
+        }
+    }
+
+    private static <T extends LoggerContext> T start(T context, RecordingAppender recording) {
+        ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
+        builder.setConfigurationName(context.getName());
+        builder.add(builder.newRootLogger(Level.INFO));
+        context.start(builder.build(false));
+        recording.start();
+        context.getConfiguration().getRootLogger().addAppender(recording, null, null);
+        context.updateLoggers();
+        return context;
+    }
+
+    // An appender for the log topic, whose producer adds the messages that it publishes to the list
+    @SuppressWarnings("unchecked")
+    private static LogAppender newLogAppender(List<String> published) throws Exception {
+        TypedMessageBuilder<byte[]> message = mock(TypedMessageBuilder.class, RETURNS_SELF);
+        when(message.value(any())).thenAnswer(invocation -> {
+            published.add(new String((byte[]) invocation.getArgument(0), StandardCharsets.UTF_8));
+            return message;
+        });
+        when(message.sendAsync()).thenReturn(CompletableFuture.completedFuture(null));
+        Producer<byte[]> producer = mock(Producer.class);
+        when(producer.newMessage()).thenReturn(message);
+        when(producer.closeAsync()).thenReturn(CompletableFuture.completedFuture(null));
+        ProducerBuilder<byte[]> producerBuilder = mock(ProducerBuilder.class, RETURNS_SELF);
+        when(producerBuilder.create()).thenReturn(producer);
+        PulsarClient client = mock(PulsarClient.class);
+        when(client.newProducer()).thenReturn(producerBuilder);
+        LogAppender logAppender = new LogAppender(client, "log-topic", "tenant/namespace/function", "0");
+        logAppender.start();
+        return logAppender;
+    }
+
+    private static void assertDetached(LoggerContext context, LogAppender logAppender) {
+        Configuration config = context.getConfiguration();
+        assertFalse(config.getRootLogger().getAppenders().containsKey(logAppender.getName()));
+        assertTrue(config.getLoggers().values().stream()
+                .noneMatch(loggerConfig -> loggerConfig.getAppenders().containsKey(logAppender.getName())));
+    }
+
+    // Records the messages of the events that it receives, and holds the thread that hands it the event "block" until
+    // released
+    private static final class RecordingAppender extends AbstractAppender {
+        private final List<String> received = new CopyOnWriteArrayList<>();
+        private final CountDownLatch blocked = new CountDownLatch(1);
+        private final CountDownLatch release = new CountDownLatch(1);
+
+        RecordingAppender() {
+            super("recording", null, null, true, Property.EMPTY_ARRAY);
+        }
+
+        @Override
+        public void append(LogEvent event) {
+            String message = event.getMessage().getFormattedMessage();
+            received.add(message);
+            if (message.equals("block")) {
+                blocked.countDown();
+                try {
+                    release.await();
+                } catch (InterruptedException e) {
+                    Thread.currentThread().interrupt();
+                }
+            }
+        }
+    }
+}