org.graylog2.gelfclient.GelfMessageBuilder Java Examples

The following examples show how to use org.graylog2.gelfclient.GelfMessageBuilder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GelfMessageJsonEncoderTest.java    From gelfclient with Apache License 2.0 5 votes vote down vote up
@BeforeMethod
public void setup() {
    channel = new EmbeddedChannel(new GelfMessageJsonEncoder());
    message = new GelfMessageBuilder("test")
            .fullMessage("The full message!")
            .level(GelfMessageLevel.INFO)
            .additionalField("_foo", 1.0)
            .additionalField("_bar", 128)
            .additionalField("_baz", "a value")
            .build();

    assertTrue(channel.writeOutbound(message));
    assertTrue(channel.finish());
}
 
Example #2
Source File: GelfclientAppender.java    From play2-graylog2 with Apache License 2.0 5 votes vote down vote up
private GelfMessage convertToGelfMessage(ILoggingEvent event) {
    return new GelfMessageBuilder(event.getFormattedMessage(), hostname)
            .timestamp(event.getTimeStamp() / 1000d)
            .level(toGelfMessageLevel(event.getLevel()))
            .additionalField("threadname", event.getThreadName())
            .additionalField("logger", event.getLoggerName())
            .build();
}
 
Example #3
Source File: GelfAppender.java    From logback-gelf-appender with Apache License 2.0 4 votes vote down vote up
@Override
protected void append(ILoggingEvent event) {

    if (event == null) {
        return;
    }

    // create a copy of the logging event to avoid passing exception stacktraces to GELF's short_message field
    LoggingEvent copy = new LoggingEvent();
    copy.setMessage(event.getMessage());
    copy.setLevel(event.getLevel());
    copy.setArgumentArray(event.getArgumentArray());
    copy.setLoggerName(event.getLoggerName());
    copy.setThreadName(event.getThreadName());
    copy.setTimeStamp(event.getTimeStamp());
    copy.setMDCPropertyMap(event.getMDCPropertyMap());

    final GelfMessageBuilder builder = new GelfMessageBuilder(this.layout.doLayout(copy), hostName).timestamp(
                event.getTimeStamp() / 1000d)
            .level(GelfMessageLevel.fromNumericLevel(toGelfNumericValue(event.getLevel())))
            .additionalField("loggerName", event.getLoggerName())
            .additionalField("threadName", event.getThreadName());

    final Marker marker = event.getMarker();

    if (marker != null) {
        builder.additionalField("marker", marker.getName());
    }

    if (includeMDC) {
        for (Map.Entry<String, String> entry : event.getMDCPropertyMap().entrySet()) {
            builder.additionalField(entry.getKey(), entry.getValue());
        }
    }

    final StackTraceElement[] callerData = event.getCallerData();

    if (includeSource && event.hasCallerData() && callerData.length > 0) {
        StackTraceElement source = callerData[0];

        builder.additionalField("sourceFileName", source.getFileName());
        builder.additionalField("sourceMethodName", source.getMethodName());
        builder.additionalField("sourceClassName", source.getClassName());
        builder.additionalField("sourceLineNumber", source.getLineNumber());
    }

    final IThrowableProxy thrown = event.getThrowableProxy();

    if (includeStackTrace && thrown != null) {
        String convertedThrowable = throwableConverter.convert(event);

        builder.additionalField("exceptionClass", thrown.getClassName());
        builder.additionalField("exceptionMessage", thrown.getMessage());
        builder.additionalField("exceptionStackTrace", convertedThrowable);

        builder.fullMessage(event.getFormattedMessage() + "\n\n" + convertedThrowable);
    } else {
        builder.fullMessage(event.getFormattedMessage());
    }

    if (includeLevelName) {
        builder.additionalField("levelName", event.getLevel().levelStr);
    }

    if (!additionalFields.isEmpty()) {
        builder.additionalFields(additionalFields);
    }

    if(!client.trySend(builder.build())) {
        addError("Failed to write log event to the GELF server using trySend");
    }
}
 
Example #4
Source File: GelfMessageJsonEncoderTest.java    From gelfclient with Apache License 2.0 4 votes vote down vote up
@Test
public void testOptionalFullMessage() throws Exception {
    final EmbeddedChannel channel = new EmbeddedChannel(new GelfMessageJsonEncoder());
    final GelfMessage message = new GelfMessageBuilder("test").build();
    assertTrue(channel.writeOutbound(message));
    assertTrue(channel.finish());

    final ByteBuf byteBuf = (ByteBuf) channel.readOutbound();
    final byte[] bytes = new byte[byteBuf.readableBytes()];
    byteBuf.getBytes(0, bytes).release();
    final JsonFactory json = new JsonFactory();
    final JsonParser parser = json.createParser(bytes);

    String version = null;
    Number timestamp = null;
    String host = null;
    String short_message = null;
    String full_message = null;
    Number level = null;

    while (parser.nextToken() != JsonToken.END_OBJECT) {
        String key = parser.getCurrentName();

        if (key == null) {
            continue;
        }

        parser.nextToken();

        switch (key) {
            case "version":
                version = parser.getText();
                break;
            case "timestamp":
                timestamp = parser.getNumberValue();
                break;
            case "host":
                host = parser.getText();
                break;
            case "short_message":
                short_message = parser.getText();
                break;
            case "full_message":
                full_message = parser.getText();
                break;
            case "level":
                level = parser.getNumberValue();
                break;
            default:
                throw new Exception("Found unexpected field in JSON payload: " + key);
        }
    }

    assertEquals(message.getVersion().toString(), version);
    assertEquals(message.getTimestamp(), timestamp);
    assertEquals(message.getHost(), host);
    assertEquals(message.getMessage(), short_message);
    assertNull(full_message);
    assertEquals(message.getLevel().getNumericLevel(), level);
}
 
Example #5
Source File: GelfMessageJsonEncoderTest.java    From gelfclient with Apache License 2.0 4 votes vote down vote up
@Test
public void testNullLevel() throws Exception {
    final EmbeddedChannel channel = new EmbeddedChannel(new GelfMessageJsonEncoder());
    final GelfMessage message = new GelfMessageBuilder("test").build();

    message.setLevel(null);

    assertTrue(channel.writeOutbound(message));
    assertTrue(channel.finish());

    final ByteBuf byteBuf = (ByteBuf) channel.readOutbound();
    final byte[] bytes = new byte[byteBuf.readableBytes()];
    byteBuf.getBytes(0, bytes).release();
    final JsonFactory json = new JsonFactory();
    final JsonParser parser = json.createParser(bytes);

    String version = null;
    Number timestamp = null;
    String host = null;
    String short_message = null;
    String full_message = null;
    Number level = null;

    while (parser.nextToken() != JsonToken.END_OBJECT) {
        String key = parser.getCurrentName();

        if (key == null) {
            continue;
        }

        parser.nextToken();

        switch (key) {
            case "version":
                version = parser.getText();
                break;
            case "timestamp":
                timestamp = parser.getNumberValue();
                break;
            case "host":
                host = parser.getText();
                break;
            case "short_message":
                short_message = parser.getText();
                break;
            case "full_message":
                full_message = parser.getText();
                break;
            case "level":
                level = parser.getNumberValue();
                break;
            default:
                throw new Exception("Found unexpected field in JSON payload: " + key);
        }
    }

    assertEquals(message.getVersion().toString(), version);
    assertEquals(message.getTimestamp(), timestamp);
    assertEquals(message.getHost(), host);
    assertEquals(message.getMessage(), short_message);
    assertNull(full_message);
    assertNull(level);
}
 
Example #6
Source File: GelfAppender.java    From log4j2-gelf with Apache License 2.0 4 votes vote down vote up
@Override
public void append(LogEvent event) {
    final Layout<? extends Serializable> layout = getLayout();
    final String formattedMessage;
    if (layout == null) {
        formattedMessage = event.getMessage().getFormattedMessage();
    } else {
        formattedMessage = new String(layout.toByteArray(event), StandardCharsets.UTF_8);
    }

    final GelfMessageBuilder builder = new GelfMessageBuilder(formattedMessage, hostName)
            .timestamp(event.getTimeMillis() / 1000d)
            .level(GelfMessageLevel.fromNumericLevel(Severity.getSeverity(event.getLevel()).getCode()))
            .additionalField("loggerName", event.getLoggerName())
            .additionalField("threadName", event.getThreadName());

    final Marker marker = event.getMarker();
    if (marker != null) {
        builder.additionalField("marker", marker.getName());
    }

    if (includeThreadContext) {
        for (Map.Entry<String, String> entry : event.getContextMap().entrySet()) {
            builder.additionalField(entry.getKey(), entry.getValue());
        }

        // Guard against https://issues.apache.org/jira/browse/LOG4J2-1530
        final ThreadContext.ContextStack contextStack = event.getContextStack();
        if (contextStack != null) {
            final List<String> contextStackItems = contextStack.asList();
            if (contextStackItems != null && !contextStackItems.isEmpty()) {
                builder.additionalField("contextStack", contextStackItems.toString());
            }
        }
    }

    if (includeSource) {
        final StackTraceElement source = event.getSource();
        if (source != null) {
            builder.additionalField("sourceFileName", source.getFileName());
            builder.additionalField("sourceMethodName", source.getMethodName());
            builder.additionalField("sourceClassName", source.getClassName());
            builder.additionalField("sourceLineNumber", source.getLineNumber());
        }
    }

    @SuppressWarnings("all")
    final Throwable thrown = event.getThrown();
    if (includeStackTrace && thrown != null) {
        String stackTrace;
        if (includeExceptionCause) {
            final StringWriter stringWriter = new StringWriter();
            final PrintWriter printWriter = new PrintWriter(stringWriter);
            thrown.printStackTrace(printWriter);
            stackTrace = stringWriter.toString();
        } else {
            stackTrace = getSimpleStacktraceAsString(thrown);
        }

        builder.additionalField("exceptionClass", thrown.getClass().getCanonicalName());
        builder.additionalField("exceptionMessage", thrown.getMessage());
        builder.additionalField("exceptionStackTrace", stackTrace);

        builder.fullMessage(formattedMessage);
    }

    if (!additionalFields.isEmpty()) {
        builder.additionalFields(additionalFields);
    }

    final GelfMessage gelfMessage = builder.build();
    try {
        final boolean sent = client.trySend(gelfMessage);
        if (!sent) {
            LOG.debug("Couldn't send message: {}", gelfMessage);
        }
    } catch (Exception e) {
        throw new AppenderLoggingException("failed to write log event to GELF server: " + e.getMessage(), e);
    }
}