All Downloads are FREE. Search and download functionalities are using the official Maven repository.

biz.paluch.logging.gelf.intern.sender.KafkaGelfSender Maven / Gradle / Ivy

The newest version!
package biz.paluch.logging.gelf.intern.sender;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;

import biz.paluch.logging.gelf.intern.ErrorReporter;
import biz.paluch.logging.gelf.intern.GelfMessage;
import biz.paluch.logging.gelf.intern.GelfSender;

/**
 * {@link GelfSender} using Kafka.
 *
 * @author Rifat Döver
 * @since 1.13
 */
public class KafkaGelfSender implements GelfSender {

    private final KafkaProducer kafkaProducer;
    private final String topicName;
    private final ErrorReporter errorReporter;

    public KafkaGelfSender(KafkaProducer kafkaProducer, String topicName, ErrorReporter errorReporter) {
        this.kafkaProducer = kafkaProducer;
        this.topicName = topicName;
        this.errorReporter = errorReporter;
    }

    @Override
    public boolean sendMessage(GelfMessage message) {
        ProducerRecord record = new ProducerRecord<>(topicName,
                message.toJson().getBytes(StandardCharsets.UTF_8));
        boolean hasOffset;
        try {
            Future metadata = kafkaProducer.send(record);
            hasOffset = metadata.get(30, TimeUnit.SECONDS).hasOffset();
        } catch (Exception e) {
            errorReporter.reportError("Error sending log to kafka", e);
            return false;
        }
        return hasOffset;
    }

    @Override
    public void close() {
        kafkaProducer.close();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy