Recommand · October 14, 2021 0

KafkaAppender for log4j2 prevents my app from terminating

I have created a simple java HelloWorld app. When I start Kafka and then the app, all messages are logged to Kafka and my app finishes with exit code 0. However, the app never finishes if I do not start Kafka beforehand. It keeps waiting till Kafka is available then it logs all messages and terminates with exit code 0.

How can I force log4j2 to terminate without having to start Kafka? I tried

LogManager.shutdown();

but it has no affect. Thank you.

HelloWorld

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LifeCycle;

public class HelloWorld {
    private static final Logger logger = LogManager.getLogger(HelloWorld.class);

    public static void main(String[] args) throws InterruptedException {
        logger.info("test1");
        logger.error("test2");

        LogManager.shutdown();
    }
}

log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" shutdownHook="true">
    <Appenders>
        <Kafka name="Kafka" topic="mylog-events" syncSend="true">
            <JsonTemplateLayout eventTemplateUri="classpath:jsonLayout.json"/>
            <Property name="bootstrap.servers">localhost:9092</Property>
        </Kafka>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%p] - %t - %m%n"/>
        </Console>
        <Async name="AsyncKafka">
            <AppenderRef ref="Kafka"/>
        </Async>
    </Appenders>
    <Loggers>
        <AsyncLogger name="org.apache.kafka" level="INFO" additivity="false">
            <AppenderRef ref="Console"/>
        </AsyncLogger>
        <AsyncRoot level="DEBUG">
            <AppenderRef ref="Console"/>
            <AppenderRef ref="AsyncKafka"/>
        </AsyncRoot>
    </Loggers>
</Configuration>

Maven dependencies

<dependencies>
    <!-- Apache Kafka Clients-->
    <dependency>
        <groupId>org.apache.kafka</groupId>
        <artifactId>kafka-clients</artifactId>
        <version>3.0.0</version>
    </dependency>
    <!-- Apache Kafka Streams-->
    <dependency>
        <groupId>org.apache.kafka</groupId>
        <artifactId>kafka-streams</artifactId>
        <version>3.0.0</version>
    </dependency>
    <!-- Apache Log4J2 binding for SLF4J -->
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-slf4j-impl</artifactId>
        <version>2.14.1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-layout-template-json</artifactId>
        <version>2.14.1</version>
    </dependency>

    <dependency>
        <groupId>com.lmax</groupId>
        <artifactId>disruptor</artifactId>
        <version>3.4.4</version>
    </dependency>
</dependencies>