@Test public void testAppend() throws Exception { wireMockRule.stubFor(post(urlEqualTo("/test/log4j/")) .willReturn(SUCCESS_RESPONSE)); final Appender appender = HttpAppender.newBuilder() .withName("Http") .withLayout(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 + "\""))); }
@Test public void testAppendHttps() throws Exception { wireMockRule.stubFor(post(urlEqualTo("/test/log4j/")) .willReturn(SUCCESS_RESPONSE)); final Appender appender = HttpAppender.newBuilder() .withName("Http") .withLayout(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(), TestConstants.KEYSTORE_TYPE, null), TrustStoreConfiguration.createKeyStoreConfiguration(TestConstants.TRUSTSTORE_FILE, TestConstants.TRUSTSTORE_PWD(), 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 + "\""))); }
@Test public void testAppendMethodPut() throws Exception { wireMockRule.stubFor(put(urlEqualTo("/test/log4j/1234")) .willReturn(SUCCESS_RESPONSE)); final Appender appender = HttpAppender.newBuilder() .withName("Http") .withLayout(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 + "\""))); }
@Test public void testAppendCustomHeader() throws Exception { wireMockRule.stubFor(post(urlEqualTo("/test/log4j/")) .willReturn(SUCCESS_RESPONSE)); final Appender appender = HttpAppender.newBuilder() .withName("Http") .withLayout(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 + "\""))); }
@Override public Layout<? extends Serializable> getOrCreateLayout(final Charset charset) { if (getLayout() == null) { return JsonLayout.newBuilder() .setCompact(true) .setCharset(charset) .setIncludeStacktrace(true) .setLocationInfo(true) .setProperties(true) .build(); } return getLayout(); }
@Override public ElasticsearchAppender build() { if (name == null) { throw new ConfigurationException("No name provided for Elasticsearch appender"); } if (batchDelivery == null) { throw new ConfigurationException("No batchDelivery [AsyncBatchDelivery] provided for Elasticsearch appender"); } if (layout == null) { layout = JsonLayout.newBuilder().setCompact(true).build(); } return new ElasticsearchAppender(name, filter, layout, ignoreExceptions, batchDelivery, messageOnly, indexNameFormatter); }
@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() .withName("Http") .withLayout(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()); }
@Test(expected = AppenderLoggingException.class) public void testAppendError() throws Exception { wireMockRule.stubFor(post(urlEqualTo("/test/log4j/")) .willReturn(FAILURE_RESPONSE)); final Appender appender = HttpAppender.newBuilder() .withName("Http") .withLayout(JsonLayout.createDefaultLayout()) .setConfiguration(ctx.getConfiguration()) .withIgnoreExceptions(false) .setUrl(new URL("http://localhost:" + wireMockRule.port() + "/test/log4j/")) .build(); appender.append(createLogEvent()); }
@Test(expected = AppenderLoggingException.class) public void testAppendConnectError() throws Exception { final Appender appender = HttpAppender.newBuilder() .withName("Http") .withLayout(JsonLayout.createDefaultLayout()) .setConfiguration(ctx.getConfiguration()) .withIgnoreExceptions(false) .setUrl(new URL("http://localhost:"+(wireMockRule.port()+1)+"/test/log4j/")) .build(); appender.append(createLogEvent()); }
@Test public void testDefaultProtocol() throws Exception { // @formatter:off final SocketAppender appender = SocketAppender.newBuilder() .withPort(tcpServer.getLocalPort()) .withReconnectDelayMillis(-1) .withName("test") .withImmediateFail(false) .withLayout(JsonLayout.newBuilder().setProperties(true).build()) .build(); // @formatter:on assertNotNull(appender); appender.stop(); }
@Test public void testUdpAppender() throws Exception { try { udpServer.latch.await(); } catch (final InterruptedException ex) { ex.printStackTrace(); } // @formatter:off final SocketAppender appender = SocketAppender.newBuilder() .withProtocol(Protocol.UDP) .withPort(tcpServer.getLocalPort()) .withReconnectDelayMillis(-1) .withName("test") .withImmediateFail(false) .withLayout(JsonLayout.newBuilder().setProperties(true).build()) .build(); // @formatter:on appender.start(); // set appender on root and set level to debug logger.addAppender(appender); logger.setAdditive(false); logger.setLevel(Level.DEBUG); logger.debug("This is a udp message"); final LogEvent event = udpServer.getQueue().poll(3, TimeUnit.SECONDS); assertNotNull("No event retrieved", event); assertTrue("Incorrect event", event.getMessage().getFormattedMessage().equals("This is a udp message")); assertTrue("Message not delivered via UDP", udpServer.getCount() > 0); }
@Test public void testTcpAppenderDeadlock() throws Exception { // @formatter:off final SocketAppender appender = SocketAppender.newBuilder() .withHost("localhost") .withPort(DYN_PORT) .withReconnectDelayMillis(100) .withName("test") .withImmediateFail(false) .withLayout(JsonLayout.newBuilder().setProperties(true).build()) .build(); // @formatter:on appender.start(); // set appender on root and set level to debug logger.addAppender(appender); logger.setAdditive(false); logger.setLevel(Level.DEBUG); final TcpSocketTestServer tcpSocketServer = new TcpSocketTestServer(DYN_PORT); try { tcpSocketServer.start(); logger.debug("This message is written because a deadlock never."); final LogEvent event = tcpSocketServer.getQueue().poll(3, TimeUnit.SECONDS); assertNotNull("No event retrieved", event); } finally { tcpSocketServer.shutdown(); } }
@Test public void testTcpAppenderNoWait() throws Exception { // @formatter:off final SocketAppender appender = SocketAppender.newBuilder() .withHost("localhost") .withPort(ERROR_PORT) .withReconnectDelayMillis(100) .withName("test") .withImmediateFail(false) .withIgnoreExceptions(false) .withLayout(JsonLayout.newBuilder().setProperties(true).build()) .build(); // @formatter:on appender.start(); // set appender on root and set level to debug logger.addAppender(appender); logger.setAdditive(false); logger.setLevel(Level.DEBUG); try { logger.debug("This message is written because a deadlock never."); fail("No Exception was thrown"); } catch (final Exception ex) { // TODO: move exception to @Test(expect = Exception.class) // Failure is expected. // ex.printStackTrace(); } }
/** * Tests for Builder for both HttpAddress and ElasticSearchRestAppender. * * @throws Exception the exception */ @Test public void builderTests() throws Exception { InetAddress address = InetAddress.getByName("invalid.hostname.com"); HttpAddress host = HttpAddress.newBuilder() .withHost(address) .withPort(123) .withScheme("https") .build(); assertEquals("invalid.hostname.com", host.getHostName()); assertEquals("https", host.getSchemeName()); assertEquals(123, host.getPort()); assertEquals(address, host.getAddress()); JsonLayout layout = JsonLayout.newBuilder() .setCompact(true) .setIncludeStacktrace(true) .setLocationInfo(true) .setProperties(true) .build(); ElasticSearchRestAppender appender = ElasticSearchRestAppender.newBuilder() .withName("builder-tests") .withIndex("test-index-") .withType("test-type") .withLayout(layout) .withCredentials("test-user", "test-pwd") .withDateFormat("dd-MM-yyyy") .withHosts(host) .withMaxBulkSize(123) .withMaxDelayTime(1234L) .withIgnoreExceptions(false) .build(); assertEquals(123, appender.getMaxBulkSize()); assertEquals(1234L, appender.getMaxDelayTime()); Calendar calendar = Calendar.getInstance(); calendar.set(2013, 11, 05); assertEquals("05-12-2013", appender.getDateFormat().format(calendar.getTime())); assertEquals(ElasticBulkSender.class, appender.getBulkSender().getClass()); ElasticBulkSender sender = (ElasticBulkSender)appender.getBulkSender(); assertEquals(1, sender.getHosts().length); assertEquals(host.getHttpHost(), sender.getHosts()[0]); assertNotNull(sender.getRestClient()); assertEquals("test-user", sender.getUser()); assertEquals("test-pwd", sender.getPassword()); assertEquals("test-index-", appender.getIndex()); assertEquals("test-type", appender.getType()); assertEquals(layout, appender.getLayout()); }
static void testTcpAppender(final TcpSocketTestServer tcpTestServer, final Logger logger, final int bufferSize) throws Exception { // @formatter:off final SocketAppender appender = SocketAppender.newBuilder() .withHost("localhost") .withPort(tcpTestServer.getLocalPort()) .withReconnectDelayMillis(-1) .withName("test") .withImmediateFail(false) .withBufferSize(bufferSize) .withLayout(JsonLayout.newBuilder().setProperties(true).build()) .build(); // @formatter:on appender.start(); Assert.assertEquals(bufferSize, appender.getManager().getByteBuffer().capacity()); // set appender on root and set level to debug logger.addAppender(appender); logger.setAdditive(false); logger.setLevel(Level.DEBUG); final String tcKey = "UUID"; final String expectedUuidStr = UUID.randomUUID().toString(); ThreadContext.put(tcKey, expectedUuidStr); ThreadContext.push(expectedUuidStr); final String expectedExMsg = "This is a test"; try { logger.debug("This is a test message"); final Throwable child = new LoggingException(expectedExMsg); logger.error("Throwing an exception", child); logger.debug("This is another test message"); } finally { ThreadContext.remove(tcKey); ThreadContext.pop(); } Thread.sleep(250); LogEvent event = tcpTestServer.getQueue().poll(3, TimeUnit.SECONDS); assertNotNull("No event retrieved", event); assertTrue("Incorrect event", event.getMessage().getFormattedMessage().equals("This is a test message")); assertTrue("Message not delivered via TCP", tcpTestServer.getCount() > 0); assertEquals(expectedUuidStr, event.getContextData().getValue(tcKey)); event = tcpTestServer.getQueue().poll(3, TimeUnit.SECONDS); assertNotNull("No event retrieved", event); assertTrue("Incorrect event", event.getMessage().getFormattedMessage().equals("Throwing an exception")); assertTrue("Message not delivered via TCP", tcpTestServer.getCount() > 1); assertEquals(expectedUuidStr, event.getContextStack().pop()); assertNotNull(event.getThrownProxy()); assertEquals(expectedExMsg, event.getThrownProxy().getMessage()); }