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

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

There is a newer version: 1.15.1
Show newest version
package biz.paluch.logging.gelf.intern.sender;

import biz.paluch.logging.gelf.intern.ErrorReporter;
import biz.paluch.logging.gelf.intern.GelfMessage;
import biz.paluch.logging.gelf.intern.GelfSender;
import redis.clients.jedis.Jedis;
import redis.clients.util.Pool;

import java.io.IOException;
import java.util.Collections;
import java.util.Set;
import java.util.WeakHashMap;

/**
 * @author https://github.com/strima/logstash-gelf.git
 * @author Mark Paluch
 * @since 1.5
 */
public class GelfREDISSender implements GelfSender {

    private final Pool jedisPool;
    private final ErrorReporter errorReporter;
    private final String redisKey;
    private final Set callers = Collections.newSetFromMap(new WeakHashMap());

    public GelfREDISSender(Pool jedisPool, String redisKey, ErrorReporter errorReporter) throws IOException {
        this.jedisPool = jedisPool;
        this.errorReporter = errorReporter;
        this.redisKey = redisKey;
    }

    public boolean sendMessage(GelfMessage message) {

        // prevent recursive self calls caused by the Redis driver since it
        if (!callers.add(Thread.currentThread())) {
            return false;
        }

        try {
            return sendMessage0(message);
        } finally {
            callers.remove(Thread.currentThread());
        }
    }

    protected boolean sendMessage0(GelfMessage message) {
        Jedis jedisClient = null;
        try {
            jedisClient = jedisPool.getResource();
            jedisClient.lpush(redisKey, message.toJson(""));
            return true;
        } catch (Exception e) {
            errorReporter.reportError(e.getMessage(), new IOException("Cannot send REDIS data with key URI " + redisKey, e));
            return false;
        } finally {
            if (jedisClient != null) {
                jedisPool.returnResource(jedisClient);
            }
        }
    }

    public void close() {
        callers.clear();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy