Java Code Examples for org.apache.logging.log4j.core.Appender#append()

The following examples show how to use org.apache.logging.log4j.core.Appender#append() . 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: KafkaAppenderTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testAppendWithKeyLookup() throws Exception {
    final Appender appender = ctx.getRequiredAppender("KafkaAppenderWithKeyLookup");
    final LogEvent logEvent = createLogEvent();
    Date date = new Date();
    SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
    appender.append(logEvent);
    final List<ProducerRecord<byte[], byte[]>> history = kafka.history();
    assertEquals(1, history.size());
    final ProducerRecord<byte[], byte[]> item = history.get(0);
    assertNotNull(item);
    assertEquals(TOPIC_NAME, item.topic());
    byte[] keyValue = format.format(date).getBytes(StandardCharsets.UTF_8);
    assertEquals(Long.valueOf(logEvent.getTimeMillis()), item.timestamp());
    assertArrayEquals(item.key(), keyValue);
    assertEquals(LOG_MESSAGE, new String(item.value(), StandardCharsets.UTF_8));
}
 
Example 2
Source File: PulsarAppenderTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Test
public void testAppendWithKeyLookup() {
    final Appender appender = ctx.getConfiguration().getAppender("PulsarAppenderWithKeyLookup");
    final LogEvent logEvent = createLogEvent();
    Date date = new Date();
    SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
    appender.append(logEvent);
    Message<byte[]> item;
    synchronized (history) {
        assertEquals(1, history.size());
        item = history.get(0);
    }
    assertNotNull(item);
    String keyValue = format.format(date);
    assertEquals(item.getKey(), keyValue);
    assertEquals(LOG_MESSAGE, new String(item.getData(), StandardCharsets.UTF_8));
}
 
Example 3
Source File: HttpAppenderTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testAppend() throws Exception {
    wireMockRule.stubFor(post(urlEqualTo("/test/log4j/"))
        .willReturn(SUCCESS_RESPONSE));

    final Appender appender = HttpAppender.newBuilder()
        .setName("Http")
        .setLayout(JsonLayout.createDefaultLayout())
        .setConfiguration(ctx.getConfiguration())
        .setUrl(new URL("http://localhost:" + wireMockRule.port() + "/test/log4j/"))
        .build();
    appender.append(createLogEvent());

    wireMockRule.verify(postRequestedFor(urlEqualTo("/test/log4j/"))
        .withHeader("Host", containing("localhost"))
        .withHeader("Content-Type", containing("application/json"))
        .withRequestBody(containing("\"message\" : \"" + LOG_MESSAGE + "\"")));
}
 
Example 4
Source File: HttpAppenderTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testAppendHttps() throws Exception {
    wireMockRule.stubFor(post(urlEqualTo("/test/log4j/"))
        .willReturn(SUCCESS_RESPONSE));

    final Appender appender = HttpAppender.newBuilder()
        .setName("Http")
        .setLayout(JsonLayout.createDefaultLayout())
        .setConfiguration(ctx.getConfiguration())
        .setUrl(new URL("https://localhost:" + wireMockRule.httpsPort() + "/test/log4j/"))
        .setSslConfiguration(SslConfiguration.createSSLConfiguration(null,
            KeyStoreConfiguration.createKeyStoreConfiguration(TestConstants.KEYSTORE_FILE, TestConstants.KEYSTORE_PWD(), null, null, TestConstants.KEYSTORE_TYPE, null),
            TrustStoreConfiguration.createKeyStoreConfiguration(TestConstants.TRUSTSTORE_FILE, TestConstants.TRUSTSTORE_PWD(), null ,null, TestConstants.TRUSTSTORE_TYPE, null)))
        .setVerifyHostname(false)
        .build();
    appender.append(createLogEvent());

    wireMockRule.verify(postRequestedFor(urlEqualTo("/test/log4j/"))
        .withHeader("Host", containing("localhost"))
        .withHeader("Content-Type", containing("application/json"))
        .withRequestBody(containing("\"message\" : \"" + LOG_MESSAGE + "\"")));
}
 
Example 5
Source File: HttpAppenderTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testAppendMethodPut() throws Exception {
    wireMockRule.stubFor(put(urlEqualTo("/test/log4j/1234"))
        .willReturn(SUCCESS_RESPONSE));

    final Appender appender = HttpAppender.newBuilder()
        .setName("Http")
        .setLayout(JsonLayout.createDefaultLayout())
        .setConfiguration(ctx.getConfiguration())
        .setMethod("PUT")
        .setUrl(new URL("http://localhost:" + wireMockRule.port() + "/test/log4j/1234"))
        .build();
    appender.append(createLogEvent());

    wireMockRule.verify(putRequestedFor(urlEqualTo("/test/log4j/1234"))
        .withHeader("Host", containing("localhost"))
        .withHeader("Content-Type", containing("application/json"))
        .withRequestBody(containing("\"message\" : \"" + LOG_MESSAGE + "\"")));
}
 
Example 6
Source File: HttpAppenderTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testAppendCustomHeader() throws Exception {
    wireMockRule.stubFor(post(urlEqualTo("/test/log4j/"))
        .willReturn(SUCCESS_RESPONSE));

    final Appender appender = HttpAppender.newBuilder()
        .setName("Http")
        .setLayout(JsonLayout.createDefaultLayout())
        .setConfiguration(ctx.getConfiguration())
        .setUrl(new URL("http://localhost:" + wireMockRule.port() + "/test/log4j/"))
        .setHeaders(new Property[] {
            Property.createProperty("X-Test", "header value"),
            Property.createProperty("X-Runtime", "${java:runtime}")
        })
        .build();
    appender.append(createLogEvent());

    wireMockRule.verify(postRequestedFor(urlEqualTo("/test/log4j/"))
        .withHeader("Host", containing("localhost"))
        .withHeader("X-Test", equalTo("header value"))
        .withHeader("X-Runtime", equalTo(JAVA_LOOKUP.getRuntime()))
        .withHeader("Content-Type", containing("application/json"))
        .withRequestBody(containing("\"message\" : \"" + LOG_MESSAGE + "\"")));
}
 
Example 7
Source File: HttpAppenderTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testAppendErrorIgnore() throws Exception {
    wireMockRule.stubFor(post(urlEqualTo("/test/log4j/"))
        .willReturn(FAILURE_RESPONSE));

    StatusLogger.getLogger().registerListener(new StatusListener() {
        @Override
        public void log(final StatusData data) {
            error = data;
        }

        @Override
        public Level getStatusLevel() {
            return Level.ERROR;
        }

        @Override
        public void close() throws IOException { }
    });

    error = null;

    final Appender appender = HttpAppender.newBuilder()
        .setName("Http")
        .setLayout(JsonLayout.createDefaultLayout())
        .setConfiguration(ctx.getConfiguration())
        .setUrl(new URL("http://localhost:" + wireMockRule.port() + "/test/log4j/"))
        .build();
    appender.append(createLogEvent());

    wireMockRule.verify(postRequestedFor(urlEqualTo("/test/log4j/"))
        .withHeader("Host", containing("localhost"))
        .withHeader("Content-Type", containing("application/json"))
        .withRequestBody(containing("\"message\" : \"" + LOG_MESSAGE + "\"")));

    assertNotNull(error);
    assertEquals(Level.ERROR, error.getLevel());
    assertEquals("Unable to send HTTP in appender [Http]", error.getMessage().toString());
}
 
Example 8
Source File: KafkaAppenderTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testAppenderNoEventTimestamp() throws Exception {
    final Appender appender = ctx.getRequiredAppender("KafkaAppenderNoEventTimestamp");
    final LogEvent logEvent = createLogEvent();
    appender.append(logEvent);
    final List<ProducerRecord<byte[], byte[]>> history = kafka.history();
    assertEquals(1, history.size());
    final ProducerRecord<byte[], byte[]> item = history.get(0);
    assertNotNull(item);
    assertEquals(TOPIC_NAME, item.topic());
    byte[] keyValue = "key".getBytes(StandardCharsets.UTF_8);
    assertArrayEquals(item.key(), keyValue);
    assertNotEquals(Long.valueOf(logEvent.getTimeMillis()), item.timestamp());
    assertEquals(LOG_MESSAGE, new String(item.value(), StandardCharsets.UTF_8));
}
 
Example 9
Source File: KafkaAppenderTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testAppendWithKey() throws Exception {
    final Appender appender = ctx.getRequiredAppender("KafkaAppenderWithKey");
    final LogEvent logEvent = createLogEvent();
    appender.append(logEvent);
    final List<ProducerRecord<byte[], byte[]>> history = kafka.history();
    assertEquals(1, history.size());
    final ProducerRecord<byte[], byte[]> item = history.get(0);
    assertNotNull(item);
    assertEquals(TOPIC_NAME, item.topic());
    byte[] keyValue = "key".getBytes(StandardCharsets.UTF_8);
    assertEquals(Long.valueOf(logEvent.getTimeMillis()), item.timestamp());
    assertArrayEquals(item.key(), keyValue);
    assertEquals(LOG_MESSAGE, new String(item.value(), StandardCharsets.UTF_8));
}
 
Example 10
Source File: KafkaAppenderTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testAsyncAppend() throws Exception {
    final Appender appender = ctx.getRequiredAppender("AsyncKafkaAppender");
    appender.append(createLogEvent());
    final List<ProducerRecord<byte[], byte[]>> history = kafka.history();
    assertEquals(1, history.size());
    final ProducerRecord<byte[], byte[]> item = history.get(0);
    assertNotNull(item);
    assertEquals(TOPIC_NAME, item.topic());
    assertNull(item.key());
    assertEquals(LOG_MESSAGE, new String(item.value(), StandardCharsets.UTF_8));
}
 
Example 11
Source File: KafkaAppenderTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testAppendWithLayout() throws Exception {
    final Appender appender = ctx.getRequiredAppender("KafkaAppenderWithLayout");
    appender.append(createLogEvent());
    final List<ProducerRecord<byte[], byte[]>> history = kafka.history();
    assertEquals(1, history.size());
    final ProducerRecord<byte[], byte[]> item = history.get(0);
    assertNotNull(item);
    assertEquals(TOPIC_NAME, item.topic());
    assertNull(item.key());
    assertEquals("[" + LOG_MESSAGE + "]", new String(item.value(), StandardCharsets.UTF_8));
}
 
Example 12
Source File: HttpAppenderTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test(expected = AppenderLoggingException.class)
public void testAppendConnectError() throws Exception {
    final Appender appender = HttpAppender.newBuilder()
        .setName("Http")
        .setLayout(JsonLayout.createDefaultLayout())
        .setConfiguration(ctx.getConfiguration())
        .setIgnoreExceptions(false)
        .setUrl(new URL("http://localhost:"+(wireMockRule.port()+1)+"/test/log4j/"))
        .build();
    appender.append(createLogEvent());
}
 
Example 13
Source File: HttpAppenderTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test(expected = AppenderLoggingException.class)
public void testAppendError() throws Exception {
    wireMockRule.stubFor(post(urlEqualTo("/test/log4j/"))
        .willReturn(FAILURE_RESPONSE));

    final Appender appender = HttpAppender.newBuilder()
        .setName("Http")
        .setLayout(JsonLayout.createDefaultLayout())
        .setConfiguration(ctx.getConfiguration())
        .setIgnoreExceptions(false)
        .setUrl(new URL("http://localhost:" + wireMockRule.port() + "/test/log4j/"))
        .build();
    appender.append(createLogEvent());
}
 
Example 14
Source File: PulsarAppenderTest.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Test
public void testAppendWithLayout() throws Exception {
    final Appender appender = ctx.getConfiguration().getAppender("PulsarAppenderWithLayout");
    appender.append(createLogEvent());
    final Message<byte[]> item;
    synchronized (history) {
        assertEquals(1, history.size());
        item = history.get(0);
    }
    assertNotNull(item);
    assertFalse(item.hasKey());
    assertEquals("[" + LOG_MESSAGE + "]", new String(item.getData(), StandardCharsets.UTF_8));
}
 
Example 15
Source File: PulsarAppenderTest.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Test
public void testAppendWithKey() {
    final Appender appender = ctx.getConfiguration().getAppender("PulsarAppenderWithKey");
    final LogEvent logEvent = createLogEvent();
    appender.append(logEvent);
    Message<byte[]> item;
    synchronized (history) {
        assertEquals(1, history.size());
        item = history.get(0);
    }
    assertNotNull(item);
    String msgKey = item.getKey();
    assertEquals(msgKey, "key");
    assertEquals(LOG_MESSAGE, new String(item.getData(), StandardCharsets.UTF_8));
}
 
Example 16
Source File: PulsarAppenderTest.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Test
public void testAsyncAppend() {
    final Appender appender = ctx.getConfiguration().getAppender("AsyncPulsarAppender");
    appender.append(createLogEvent());
    final Message<byte[]> item;
    synchronized (history) {
        assertEquals(1, history.size());
        item = history.get(0);
    }
    assertNotNull(item);
    assertFalse(item.hasKey());
    assertEquals(LOG_MESSAGE, new String(item.getData(), StandardCharsets.UTF_8));
}
 
Example 17
Source File: PulsarAppenderTest.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Test
public void testAppendWithSerializedLayout() throws Exception {
    final Appender appender = ctx.getConfiguration().getAppender("PulsarAppenderWithSerializedLayout");
    final LogEvent logEvent = createLogEvent();
    appender.append(logEvent);
    final Message<byte[]> item;
    synchronized (history) {
        assertEquals(1, history.size());
        item = history.get(0);
    }
    assertNotNull(item);
    assertFalse(item.hasKey());
    assertEquals(LOG_MESSAGE, deserializeLogEvent(item.getData()).getMessage().getFormattedMessage());
}
 
Example 18
Source File: LogstashIT.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Test
public void test_newlines() throws IOException {

    // Create two log events containing new lines.
    final Level level = Level.DEBUG;
    final String loggerFqcn = "f.q.c.n";
    final String loggerName = "A";
    final SimpleMessage message1 = new SimpleMessage("line1\nline2\r\nline3");
    final long instantMillis1 = Instant.EPOCH.toEpochMilli();
    final LogEvent logEvent1 = Log4jLogEvent
            .newBuilder()
            .setLoggerName(loggerName)
            .setLoggerFqcn(loggerFqcn)
            .setLevel(level)
            .setMessage(message1)
            .setTimeMillis(instantMillis1)
            .build();
    final SimpleMessage message2 = new SimpleMessage("line4\nline5\r\nline6");
    final long instantMillis2 = instantMillis1 + Duration.ofDays(1).toMillis();
    final LogEvent logEvent2 = Log4jLogEvent
            .newBuilder()
            .setLoggerName(loggerName)
            .setLoggerFqcn(loggerFqcn)
            .setLevel(level)
            .setMessage(message2)
            .setTimeMillis(instantMillis2)
            .build();

    try (final RestHighLevelClient client = createClient()) {
        final Appender appender = createStartedAppender(
                JSON_TEMPLATE_GELF_LAYOUT,
                MavenHardcodedConstants.LS_GELF_INPUT_PORT);
        try {

            // Append the event.
            LOGGER.info("appending events");
            appender.append(logEvent1);
            appender.append(logEvent2);
            LOGGER.info("completed appending events");

            // Wait the message to arrive.
            Awaitility
                    .await()
                    .atMost(Duration.ofSeconds(60))
                    .pollDelay(Duration.ofSeconds(2))
                    .until(() -> queryDocumentCount(client) == 2);

            // Verify indexed messages.
            final Set<String> expectedMessages = Stream
                    .of(logEvent1, logEvent2)
                    .map(LogstashIT::expectedLogstashMessageField)
                    .collect(Collectors.toSet());
            final Set<String> actualMessages = queryDocuments(client)
                    .stream()
                    .map(source -> (String) source.get(ES_INDEX_MESSAGE_FIELD_NAME))
                    .filter(Objects::nonNull)
                    .collect(Collectors.toSet());
            Assertions
                    .assertThat(actualMessages)
                    .isEqualTo(expectedMessages);

        } finally {
            appender.stop();
        }
    }

}