Search in sources :

Example 96 with Event

use of loghub.Event in project LogHub by fbacchella.

the class TestNsca method test.

@Test
public void test() throws ConfigException, IOException {
    String conf = "pipeline[main] {} output $main | { loghub.senders.Nsca { password: \"password\", encryption: \"RIJNDAEL192\", nagiosServer: \"localhost\", largeMessageSupport: true, mapping: { \"level\": \"level\", \"service\": \"service\",  \"message\": \"message\",  \"host\": \"host\", } } }";
    Properties p = Configuration.parse(new StringReader(conf));
    Nsca sender = (Nsca) p.senders.stream().findAny().get();
    Assert.assertTrue(sender.configure(p));
    Event ev = Event.emptyEvent(ConnectionContext.EMPTY);
    ev.put("level", "CRITICAL");
    ev.put("service", "aservice");
    ev.put("message", "message");
    ev.put("host", "host");
    sender.send(ev);
}
Also used : StringReader(java.io.StringReader) Event(loghub.Event) Properties(loghub.configuration.Properties) Test(org.junit.Test)

Example 97 with Event

use of loghub.Event in project LogHub by fbacchella.

the class Kafka method run.

@Override
public void run() {
    consumer.subscribe(Collections.singletonList(topic));
    boolean broke = false;
    while (!isInterrupted()) {
        ConsumerRecords<Long, byte[]> consumerRecords = consumer.poll(100);
        if (consumerRecords.count() == 0) {
            continue;
        }
        for (ConsumerRecord<Long, byte[]> record : consumerRecords) {
            ConnectionContext ctxt = new KafkaContext(record.topic());
            Event event = emptyEvent(ctxt);
            if (record.timestampType() == TimestampType.CREATE_TIME) {
                event.setTimestamp(new Date(record.timestamp()));
            }
            Header[] headers = record.headers().toArray();
            if (headers.length > 0) {
                Map<String, byte[]> headersMap = new HashMap<>(headers.length);
                Arrays.stream(headers).forEach(i -> headersMap.put(i.key(), i.value()));
                event.put("headers", headersMap);
            }
            byte[] content = record.value();
            try {
                event.putAll(decoder.decode(ctxt, content, 0, content.length));
                send(event);
            } catch (DecodeException e) {
                logger.error(e.getMessage());
                logger.catching(e);
            }
            if (isInterrupted()) {
                consumer.commitSync(Collections.singletonMap(new TopicPartition(record.topic(), record.partition()), new OffsetAndMetadata(record.offset())));
                broke = true;
                break;
            }
        }
        if (!broke) {
            consumer.commitAsync();
        } else {
            break;
        }
    }
    consumer.close();
}
Also used : HashMap(java.util.HashMap) DecodeException(loghub.Decoder.DecodeException) Date(java.util.Date) Header(org.apache.kafka.common.header.Header) TopicPartition(org.apache.kafka.common.TopicPartition) OffsetAndMetadata(org.apache.kafka.clients.consumer.OffsetAndMetadata) Event(loghub.Event) ConnectionContext(loghub.ConnectionContext)

Example 98 with Event

use of loghub.Event in project LogHub by fbacchella.

the class ElasticSearch method putContent.

private byte[] putContent(Batch documents) {
    StringBuilder builder = new StringBuilder();
    Map<String, String> settings = new HashMap<>(2);
    Map<String, Object> action = Collections.singletonMap("index", settings);
    Map<String, Object> esjson = new HashMap<>();
    ObjectMapper jsonmapper = json.get();
    int validEvents = 0;
    for (Event e : documents) {
        try {
            if (!e.containsKey(type)) {
                processStatus(e, CompletableFuture.completedFuture(false));
                continue;
            }
            validEvents++;
            esjson.clear();
            esjson.putAll(e);
            esjson.put("@timestamp", ISO8601.get().format(e.getTimestamp()));
            esjson.put("__index", esIndexFormat.get().format(e.getTimestamp()));
            settings.put("_type", esjson.remove(type).toString());
            settings.put("_index", esjson.remove("__index").toString());
            try {
                builder.append(jsonmapper.writeValueAsString(action));
                builder.append("\n");
                builder.append(jsonmapper.writeValueAsString(esjson));
                builder.append("\n");
            } catch (JsonProcessingException ex) {
                logger.error("Failed to serialized {}: {}", e, ex.getMessage());
                logger.catching(Level.DEBUG, ex);
            }
            processStatus(e, CompletableFuture.completedFuture(true));
        } catch (java.lang.StackOverflowError ex) {
            processStatus(e, CompletableFuture.completedFuture(false));
            logger.error("Failed to serialized {}, infinite recursion", e);
        }
    }
    if (validEvents == 0) {
        return null;
    } else {
        return builder.toString().getBytes(CharsetUtil.UTF_8);
    }
}
Also used : HashMap(java.util.HashMap) Event(loghub.Event) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 99 with Event

use of loghub.Event in project LogHub by fbacchella.

the class Gelf method encode.

@Override
public byte[] encode(Event event) {
    try {
        Map<String, Object> gelfcontent = new HashMap<>(event.size() + 5);
        gelfcontent.put("version", "1.1");
        gelfcontent.put("host", hostname);
        if (event.containsKey(shortmessagefield)) {
            gelfcontent.put("short_message", event.remove(shortmessagefield));
        }
        if (fullmessagefield != null && event.containsKey(fullmessagefield)) {
            gelfcontent.put("full_message", event.remove(fullmessagefield));
        }
        gelfcontent.put("timestamp", event.getTimestamp().getTime() / 1000.0);
        event.entrySet().stream().filter(i -> !"id".equals(i.getKey())).filter(i -> fieldpredicate.test(i.getKey())).forEach(i -> gelfcontent.put("_" + i.getKey(), i.getValue()));
        byte[] buffer1 = json.get().writeValueAsBytes(gelfcontent);
        byte[] buffer2;
        if (compressed) {
            try (final ByteArrayOutputStream bos = new ByteArrayOutputStream();
                final GZIPOutputStream stream = new GZIPOutputStream(bos)) {
                stream.write(buffer1);
                stream.finish();
                buffer2 = bos.toByteArray();
            }
        } else if (stream) {
            buffer2 = Arrays.copyOf(buffer1, buffer1.length + 1);
        } else {
            buffer2 = buffer1;
        }
        return buffer2;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Also used : Arrays(java.util.Arrays) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Predicate(java.util.function.Predicate) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IOException(java.io.IOException) HashMap(java.util.HashMap) UnknownHostException(java.net.UnknownHostException) InetAddress(java.net.InetAddress) JsonFactory(com.fasterxml.jackson.core.JsonFactory) Map(java.util.Map) Encoder(loghub.Encoder) GZIPOutputStream(java.util.zip.GZIPOutputStream) Pattern(java.util.regex.Pattern) Event(loghub.Event) HashMap(java.util.HashMap) GZIPOutputStream(java.util.zip.GZIPOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException)

Example 100 with Event

use of loghub.Event in project LogHub by fbacchella.

the class Grok method processMessage.

@Override
public boolean processMessage(Event event, String field, String destination) {
    if (!event.containsKey(field)) {
        return false;
    }
    String line = event.get(field).toString();
    Match gm = grok.match(line);
    gm.captures();
    if (!gm.isNull()) {
        // Results from grok needs to be cleaned
        for (Map.Entry<String, Object> e : gm.toMap().entrySet()) {
            String destinationField = e.getKey();
            // . is a special field name, it mean a value to put back in the original field
            if (".".equals(e.getKey())) {
                destinationField = field;
            }
            // Needed until https://github.com/thekrakken/java-grok/issues/61 is fixed
            if (e.getKey().equals(e.getKey().toUpperCase()) && !".".equals(e.getKey())) {
                continue;
            }
            if (e.getValue() == null) {
                continue;
            }
            if (e.getValue() instanceof List) {
                List<?> listvalue = (List<?>) e.getValue();
                List<String> newvalues = new ArrayList<>();
                listvalue.stream().filter(i -> i != null).map(i -> i.toString()).forEach(newvalues::add);
                if (newvalues.size() == 0) {
                    continue;
                } else if (newvalues.size() == 1) {
                    event.put(destinationField, newvalues.get(0));
                } else {
                    event.put(destinationField, newvalues);
                }
            } else {
                event.put(destinationField, e.getValue());
            }
        }
        return true;
    }
    return false;
}
Also used : BufferedInputStream(java.io.BufferedInputStream) PatternSyntaxException(java.util.regex.PatternSyntaxException) GrokException(io.thekraken.grok.api.exception.GrokException) URISyntaxException(java.net.URISyntaxException) Level(org.apache.logging.log4j.Level) Match(io.thekraken.grok.api.Match) IOException(java.io.IOException) InputStreamReader(java.io.InputStreamReader) ArrayList(java.util.ArrayList) List(java.util.List) Helpers(loghub.Helpers) Map(java.util.Map) Collections(java.util.Collections) Event(loghub.Event) InputStream(java.io.InputStream) Properties(loghub.configuration.Properties) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) Map(java.util.Map) Match(io.thekraken.grok.api.Match)

Aggregations

Event (loghub.Event)102 Test (org.junit.Test)90 Properties (loghub.configuration.Properties)63 Pipeline (loghub.Pipeline)23 Date (java.util.Date)19 Map (java.util.Map)18 HashMap (java.util.HashMap)14 IOException (java.io.IOException)13 Tools (loghub.Tools)13 URL (java.net.URL)8 Collections (java.util.Collections)8 ArrayBlockingQueue (java.util.concurrent.ArrayBlockingQueue)8 Level (org.apache.logging.log4j.Level)7 List (java.util.List)6 EventsProcessor (loghub.EventsProcessor)6 LogManager (org.apache.logging.log4j.LogManager)6 Logger (org.apache.logging.log4j.Logger)6 LogUtils (loghub.LogUtils)5 ProcessorException (loghub.ProcessorException)5 Assert (org.junit.Assert)5