Java Code Examples for org.apache.logging.log4j.core.Logger#error()

The following examples show how to use org.apache.logging.log4j.core.Logger#error() . 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: SmtpAppenderAsyncTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private void testSmtpAppender(Logger logger) {
    ThreadContext.put("MDC1", "mdc1");
    logger.error("the message");
    ctx.getLoggerContext().stop();
    smtpServer.stop();

    assertEquals(1, smtpServer.getReceivedEmailSize());
    final Iterator<SmtpMessage> messages = smtpServer.getReceivedEmail();
    final SmtpMessage email = messages.next();

    assertEquals("[email protected]", email.getHeaderValue("To"));
    assertEquals("[email protected]", email.getHeaderValue("From"));
    assertEquals("[mdc1]", email.getHeaderValue("Subject"));

    String body = email.getBody();
    if (!body.contains("Body:[mdc1]")) {
        fail(body);
    }
}
 
Example 2
Source File: CsvJsonParameterLayoutFileAppenderTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
public void testNoNulCharacters(final String message, final String expected) throws IOException {
    @SuppressWarnings("resource")
    final LoggerContext loggerContext = loggerContextRule.getLoggerContext();
    final Logger logger = loggerContext.getLogger("com.example");
    logger.error("log:", message);
    loggerContext.stop();
    final File file = new File(FILE_PATH);
    final byte[] contents = FileUtils.readFileToByteArray(file);
    int count0s = 0;
    final StringBuilder sb = new StringBuilder();
    for (int i = 0; i < contents.length; i++) {
        final byte b = contents[i];
        if (b == 0) {
            sb.append(i);
            sb.append(", ");
            count0s++;
        }
    }
    Assert.assertEquals("File contains " + count0s + " 0x00 byte at indices " + sb, 0, count0s);
    final List<String> readLines = FileUtils.readLines(file, Charset.defaultCharset());
    final String actual = readLines.get(0);
    // Assert.assertTrue(actual, actual.contains(message));
    Assert.assertEquals(actual, expected, actual);
    Assert.assertEquals(1, readLines.size());
}
 
Example 3
Source File: CsvParameterLayoutTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testLogJsonArgument() throws InterruptedException {
    final ListAppender appender = (ListAppender) init.getAppender("List");
    appender.countDownLatch = new CountDownLatch(4);
    appender.clear();
    final Logger logger = (Logger) LogManager.getRootLogger();
    final String json = "{\"id\":10,\"name\":\"Alice\"}";
    logger.error("log:{}", json);
    // wait until background thread finished processing
    final int msgCount = 1;
    if (appender.getMessages().size() < msgCount) {
        appender.countDownLatch.await(5, TimeUnit.SECONDS);
    }
    assertEquals("Background thread did not finish processing: msg count", msgCount, appender.getMessages().size());

    // don't stop appender until background thread is done
    appender.stop();
    final List<String> list = appender.getMessages();
    final String eventStr = list.get(0).toString();
    Assert.assertTrue(eventStr, eventStr.contains(json));
}
 
Example 4
Source File: DefaultRouteScriptAppenderTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private void logAndCheck() {
    final Marker marker = MarkerManager.getMarker("HEXDUMP");
    final Logger logger = loggerContextRule.getLogger(DefaultRouteScriptAppenderTest.class);
    logger.error("Hello");
    final ListAppender listAppender = getListAppender();
    assertEquals("Incorrect number of events", 1, listAppender.getEvents().size());
    logger.error("World");
    assertEquals("Incorrect number of events", 2, listAppender.getEvents().size());
    logger.error(marker, "DEADBEEF");
    assertEquals("Incorrect number of events", 3, listAppender.getEvents().size());
}
 
Example 5
Source File: RoutesScriptAppenderTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private void logAndCheck() {
    final Marker marker = MarkerManager.getMarker("HEXDUMP");
    final Logger logger = loggerContextRule.getLogger(RoutesScriptAppenderTest.class);
    logger.error("Hello");
    final ListAppender listAppender = getListAppender();
    assertEquals("Incorrect number of events", 1, listAppender.getEvents().size());
    logger.error("World");
    assertEquals("Incorrect number of events", 2, listAppender.getEvents().size());
    logger.error(marker, "DEADBEEF");
    assertEquals("Incorrect number of events", 3, listAppender.getEvents().size());
}
 
Example 6
Source File: ScriptAppenderSelectorTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private void logAndCheck() {
    final Marker marker = MarkerManager.getMarker("HEXDUMP");
    final Logger logger = loggerContextRule.getLogger(ScriptAppenderSelectorTest.class);
    logger.error("Hello");
    final ListAppender listAppender = getListAppender();
    assertEquals("Incorrect number of events", 1, listAppender.getEvents().size());
    logger.error("World");
    assertEquals("Incorrect number of events", 2, listAppender.getEvents().size());
    logger.error(marker, "DEADBEEF");
    assertEquals("Incorrect number of events", 3, listAppender.getEvents().size());
}
 
Example 7
Source File: SmtpAppenderTest.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Test
public void testDelivery() {
    final String subjectKey = getClass().getName();
    final String subjectValue = "SubjectValue1";
    ThreadContext.put(subjectKey, subjectValue);
    final int smtpPort = AvailablePortFinder.getNextAvailable();
    final SmtpAppender appender = SmtpAppender.newBuilder()
            .setName("Test")
            .setTo("[email protected]")
            .setCc("[email protected]")
            .setBcc("[email protected]")
            .setFrom("[email protected]")
            .setReplyTo("[email protected]")
            .setSubject("Subject Pattern %X{" + subjectKey + "}")
            .setSmtpHost(HOST)
            .setSmtpPort(smtpPort)
            .setBufferSize(3)
            .build();
    appender.start();

    final LoggerContext context = LoggerContext.getContext();
    final Logger root = context.getLogger("SMTPAppenderTest");
    root.addAppender(appender);
    root.setAdditive(false);
    root.setLevel(Level.DEBUG);

    final SimpleSmtpServer server = SimpleSmtpServer.start(smtpPort);

    root.debug("Debug message #1");
    root.debug("Debug message #2");
    root.debug("Debug message #3");
    root.debug("Debug message #4");
    root.error("Error with exception", new RuntimeException("Exception message"));
    root.error("Error message #2");

    server.stop();
    assertTrue(server.getReceivedEmailSize() == 2);
    final Iterator<SmtpMessage> messages = server.getReceivedEmail();
    final SmtpMessage email = messages.next();

    assertEquals("[email protected]", email.getHeaderValue("To"));
    assertEquals("[email protected]", email.getHeaderValue("Cc"));
    // assertEquals("[email protected]", email.getHeaderValue("Bcc")); // BCC
    // can't be tested with Dumpster 1.6
    assertEquals("[email protected]", email.getHeaderValue("From"));
    assertEquals("[email protected]", email.getHeaderValue("Reply-To"));
    final String headerValue = email.getHeaderValue("Subject");
    assertEquals(headerValue, "Subject Pattern " + subjectValue);

    final String body = email.getBody();
    assertFalse(body.contains("Debug message #1"));
    assertTrue(body.contains("Debug message #2"));
    assertTrue(body.contains("Debug message #3"));
    assertTrue(body.contains("Debug message #4"));
    assertTrue(body.contains("Error with exception"));
    assertTrue(body.contains("RuntimeException"));
    assertTrue(body.contains("Exception message"));
    assertFalse(body.contains("Error message #2"));

    final SmtpMessage email2 = messages.next();
    final String body2 = email2.getBody();
    assertFalse(body2.contains("Debug message #4"));
    assertFalse(body2.contains("Error with exception"));
    assertTrue(body2.contains("Error message #2"));
}
 
Example 8
Source File: SocketAppenderTest.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
static void testTcpAppender(final TcpSocketTestServer tcpTestServer, final Logger logger, final int bufferSize)
        throws Exception {
    // @formatter:off
    final SocketAppender appender = SocketAppender.newBuilder()
            .setHost("localhost")
            .setPort(tcpTestServer.getLocalPort())
            .setReconnectDelayMillis(-1)
            .setName("test")
            .setImmediateFail(false)
            .setBufferSize(bufferSize)
            .setLayout(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());
}