Log4j自定义附加程序不适用于日志语句

时间:2019-04-18 15:56:31

标签: apache-kafka log4j2

我正在尝试使用Log4J附加程序将应用程序日志流式传输到kafka。

我看到启动日志被推送到kafka,但是我的应用程序日志没有发布到kafka。

做完一些研究后,我发现应用程序日志语句未在我的自定义附加程序中触发附加功能。

这是我的代码:

自定义Appender:

@Plugin(name = "Kafka", category = "Core", elementType = "appender", printObject = true)
public final class KafkaAppender extends AbstractAppender {
    public void append(LogEvent event) {
    System.out.println("##################################### Inside Log Event :"+event.toString());
    try {
        if (producer != null) {
            Future<RecordMetadata> result = producer.send(new ProducerRecord<String, String>(topic, getLayout().toSerializable(event).toString()));
            if(syncsend)
                result.get();
        }
    } catch (final Exception e) {
        LOGGER.error("Unable to write to kafka for appender [{}].",  this.getName(), e);
        throw new AppenderLoggingException("Unable to write to kafka in appender: " + e.getMessage(), e);
    } finally {
    }
}
}

Pom.xml:

    <dependency>
        <groupId>org.apache.kafka</groupId>
        <artifactId>kafka-log4j-appender</artifactId>
        <version>1.0.0</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-log4j2</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.apache.logging.log4j</groupId>
                <artifactId>log4j-slf4j-impl</artifactId>
            </exclusion>

                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-log4j12</artifactId>
                </exclusion>
        </exclusions>
    </dependency>

Log4j2.xml

<Configuration status="INFO">
<Appenders>
<Kafka name="KAFKALOGGER" topic="my-test-topic">
    <Property name="bootstrap.servers">server1,server2</Property>
</Kafka>
<Console name="console" target="SYSTEM_OUT">
    <PatternLayout pattern="%d{HH:mm:ss.SSS} %-5p [%-7t] %F:%L - %m%n"/>
</Console>
</Appenders>

<Loggers>
<Root level="INFO">
    <AppenderRef ref="console" />
    <AppenderRef ref="KAFKALOGGER" />
</Root>
<Logger name="net.test.kafka" level="INFO">
    <AppenderRef ref="console" />
    <AppenderRef ref="KAFKALOGGER" />
</Logger>
</Loggers>
</Configuration>

代码中的日志语句:

@Slf4j
@SpringBootApplication
public class MyTestApplication{
public static void main(String[] args) {

  SpringApplication application = new SpringApplication(MyTestApplication.class);
  log.info("Testing my application from MyTestApplication");
  log.error("Testing my application from MyTestApplication");
  application.run(args);
  log.info("Testing my application from MyTestApplication");
  log.error("Testing my application from MyTestApplication");
}

}

0 个答案:

没有答案