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

The following examples show how to use org.apache.logging.log4j.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: AsyncLoggersWithAsyncLoggerConfigTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testLoggingWorks() throws Exception {
    final Logger logger = LogManager.getLogger();
    logger.error("This is a test");
    logger.warn("Hello world!");
    Thread.sleep(100);
    final List<String> list = context.getListAppender("List").getMessages();
    assertNotNull("No events generated", list);
    assertTrue("Incorrect number of events. Expected 2, got " + list.size(), list.size() == 2);
    String msg = list.get(0);
    String expected = getClass().getName() + " This is a test";
    assertTrue("Expected " + expected + ", Actual " + msg, expected.equals(msg));
    msg = list.get(1);
    expected = getClass().getName() + " Hello world!";
    assertTrue("Expected " + expected + ", Actual " + msg, expected.equals(msg));
}
 
Example 2
Source File: ForwardLogHandler.java    From Kettle with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void publish(LogRecord record) {
    Logger logger = getLogger(String.valueOf(record.getLoggerName())); // See SPIGOT-1230
    Throwable exception = record.getThrown();
    Level level = record.getLevel();
    String message = getFormatter().formatMessage(record);

    if (level == Level.SEVERE) {
        logger.error(message, exception);
    } else if (level == Level.WARNING) {
        logger.warn(message, exception);
    } else if (level == Level.INFO) {
        logger.info(message, exception);
    } else if (level == Level.CONFIG) {
        logger.debug(message, exception);
    } else {
        logger.trace(message, exception);
    }
}
 
Example 3
Source File: ConsoleAppenderJAnsiXExceptionMain.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
public void test(final String[] args) {
    System.setProperty("log4j.skipJansi", "false"); // LOG4J2-2087: explicitly enable
    // System.out.println(System.getProperty("java.class.path"));
    final String config = args == null || args.length == 0 ? "target/test-classes/log4j2-console-xex-ansi.xml"
            : args[0];
    final LoggerContext ctx = Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(), config);
    final Logger logger = LogManager.getLogger(ConsoleAppenderJAnsiXExceptionMain.class);
    try {
        Files.getFileStore(Paths.get("?BOGUS?"));
    } catch (final Exception e) {
        final IllegalArgumentException logE = new IllegalArgumentException("Bad argument foo", e);
        logger.error("Gotcha!", logE);
    } finally {
        Configurator.shutdown(ctx);
    }
}
 
Example 4
Source File: AsyncLoggersWithAsyncAppenderTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testLoggingWorks() throws Exception {
    final Logger logger = LogManager.getLogger();
    logger.error("This {} a test", "is");
    logger.warn("Hello {}!", "world");
    Thread.sleep(100);
    final List<String> list = context.getListAppender("List").getMessages();
    assertNotNull("No events generated", list);
    assertEquals("Incorrect number of events ", 2, list.size());
    String msg = list.get(0);
    String expected = getClass().getName() + " This {} a test - [is] - This is a test";
    assertEquals(expected, msg);
    msg = list.get(1);
    expected = getClass().getName() + " Hello {}! - [world] - Hello world!";
    assertEquals(expected, msg);
}
 
Example 5
Source File: ThrowableProxyTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * Attempts to instantiate a class that cannot initialize and then logs the stack trace of the Error. The logger
 * must not fail when using {@link ThrowableProxy} to inspect the frames of the stack trace.
 */
@Test
public void testLogStackTraceWithClassThatCannotInitialize() {
    try {
        // Try to create the object, which will always fail during class initialization
        final AlwaysThrowsError error = new AlwaysThrowsError();

        // If the error was not triggered then fail
        fail("Test did not throw expected error: " + error);
    } catch (final Throwable e) {
        // Print the stack trace to System.out for informational purposes
        // System.err.println("### Here's the stack trace that we'll log with log4j ###");
        // e.printStackTrace();
        // System.err.println("### End stack trace ###");

        final Logger logger = LogManager.getLogger(getClass());

        // This is the critical portion of the test. The log message must be printed without
        // throwing a java.lang.Error when introspecting the AlwaysThrowError class in the
        // stack trace.
        logger.error(e.getMessage(), e);
        logger.error(e);
    }
}
 
Example 6
Source File: HTTPSpnegoAuthenticator.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
private static String getUsernameFromGSSContext(final GSSContext gssContext, final boolean strip, final Logger logger) {
    if (gssContext.isEstablished()) {
        GSSName gssName = null;
        try {
            gssName = gssContext.getSrcName();
        } catch (final GSSException e) {
            logger.error("Unable to get src name from gss context", e);
        }

        if (gssName != null) {
            String name = gssName.toString();
            return stripRealmName(name, strip);
        } else {
            logger.error("GSS name is null");
        }
    } else {
        logger.error("GSS context not established");
    }

    return null;
}
 
Example 7
Source File: AsyncAppenderNoLocationTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoLocation() throws Exception {
    final Logger logger = LogManager.getLogger(AsyncAppender.class);
    logger.error("This is a test");
    logger.warn("Hello world!");
    Thread.sleep(100);
    System.out.println("app = " + app == null ? "null" : app);
    final List<String> list = app.getMessages();
    assertNotNull("No events generated", list);
    assertEquals("Incorrect number of events. Expected 2, got " + list.size(), list.size(), 2);
    String msg = list.get(0);
    String expected = "?  This is a test";
    assertEquals("Expected " + expected + ", Actual " + msg, expected, msg);
    msg = list.get(1);
    expected = "?  Hello world!";
    assertEquals("Expected " + expected + ", Actual " + msg, expected, msg);
}
 
Example 8
Source File: AsyncAppenderQueueFullPolicyTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testRouter() throws Exception {
    final Logger logger = LogManager.getLogger(AsyncAppenderQueueFullPolicyTest.class);

    assertEquals(4, asyncAppender.getQueueCapacity());
    logger.error("event 1 - gets taken off the queue");
    logger.warn("event 2");
    logger.info("event 3");
    logger.info("event 4");
    while (asyncAppender.getQueueRemainingCapacity() == 0) {
        Thread.yield(); // wait until background thread takes one element off the queue
    }
    logger.info("event 5 - now the queue is full");
    assertEquals("queue remaining capacity", 0, asyncAppender.getQueueRemainingCapacity());
    assertEquals("EventRouter invocations", 0, policy.queueFull.get());

    final Thread release = new Thread("AsyncAppenderReleaser") {
        @Override
        public void run() {
            while (policy.queueFull.get() == 0) {
                try {
                    Thread.sleep(10L);
                } catch (final InterruptedException ignored) {
                    //ignored
                }
            }
            blockingAppender.running = false;
        }
    };
    release.setDaemon(true);
    release.start();
    logger.fatal("this blocks until queue space available");
    assertEquals(1, policy.queueFull.get());
}
 
Example 9
Source File: Log4j2IT.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Test
public void test() {
    Logger logger = LogManager.getLogger();
    logger.error("for log4j2 plugin test");

    Assert.assertNotNull(ThreadContext.get("PtxId"));
    Assert.assertNotNull(ThreadContext.get("PspanId"));
}
 
Example 10
Source File: Log4j2ForAsyncLoggerIT.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Test
public void test() {
    Logger logger = LogManager.getLogger();
    logger.error("for log4j2 plugin async logger test");

    Assert.assertNotNull(ThreadContext.get("PtxId"));
    Assert.assertNotNull(ThreadContext.get("PspanId"));
}
 
Example 11
Source File: XMLConfigLogIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenXMLConfigurationPlugin_whenSimpleLog_ThenLogsCorrectly() throws Exception {
    Logger logger = LogManager.getLogger(this.getClass());
    LoggerContext ctx = (LoggerContext) LogManager.getContext();
    logger.debug("Debug log message");
    logger.info("Info log message");
    logger.error("Error log message");
}
 
Example 12
Source File: CustomLoggingIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenLoggerWithConsoleConfig_whenFilterByMarker_thanOK() throws Exception {
    Logger logger = LogManager.getLogger("CONSOLE_PATTERN_APPENDER_MARKER");
    Marker appError = MarkerManager.getMarker("APP_ERROR");
    Marker connectionTrace = MarkerManager.getMarker("CONN_TRACE");

    logger.error(appError, "This marker message at ERROR level should be hidden.");
    logger.trace(connectionTrace, "This is a marker message at TRACE level.");
}
 
Example 13
Source File: CustomLoggingIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenLoggerWithFailoverConfig_whenLog_thanOK() throws Exception {
    Logger logger = LogManager.getLogger("FAIL_OVER_SYSLOG_APPENDER");
    Exception e = new RuntimeException("This is only a test!");

    logger.trace("This is a syslog message at TRACE level.");
    logger.debug("This is a syslog message at DEBUG level.");
    logger.info("This is a syslog message at INFO level. This is the minimum visible level.");
    logger.warn("This is a syslog message at WARN level.");
    logger.error("This is a syslog message at ERROR level.", e);
    logger.fatal("This is a syslog message at FATAL level.");
}
 
Example 14
Source File: CallerInformationTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testClassLogger() throws Exception {
    final ListAppender app = context.getListAppender("Class").clear();
    final Logger logger = context.getLogger("ClassLogger");
    logger.info("Ignored message contents.");
    logger.warn("Verifying the caller class is still correct.");
    logger.error("Hopefully nobody breaks me!");
    final List<String> messages = app.getMessages();
    assertEquals("Incorrect number of messages.", 3, messages.size());
    for (final String message : messages) {
        assertEquals("Incorrect caller class name.", this.getClass().getName(), message);
    }
}
 
Example 15
Source File: CallerInformationTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testMethodLogger() throws Exception {
    final ListAppender app = context.getListAppender("Method").clear();
    final Logger logger = context.getLogger("MethodLogger");
    logger.info("More messages.");
    logger.warn("CATASTROPHE INCOMING!");
    logger.error("ZOMBIES!!!");
    logger.fatal("brains~~~");
    logger.info("Itchy. Tasty.");
    final List<String> messages = app.getMessages();
    assertEquals("Incorrect number of messages.", 5, messages.size());
    for (final String message : messages) {
        assertEquals("Incorrect caller method name.", "testMethodLogger", message);
    }
}
 
Example 16
Source File: CustomLoggingIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenLoggerWithDefaultConfig_whenLogToConsole_thanOK() throws Exception {
    Logger logger = LogManager.getLogger(getClass());
    Exception e = new RuntimeException("This is only a test!");

    logger.info("This is a simple message at INFO level. " + "It will be hidden.");
    logger.error("This is a simple message at ERROR level. " + "This is the minimum visible level.", e);
}
 
Example 17
Source File: OutputStreamAppenderTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testOutputStreamAppenderToByteArrayOutputStream() {
    final OutputStream out = new ByteArrayOutputStream();
    final String name = getName(out);
    final Logger logger = LogManager.getLogger(name);
    addAppender(out, name);
    logger.error(TEST_MSG);
    final String actual = out.toString();
    Assert.assertTrue(actual, actual.contains(TEST_MSG));
}
 
Example 18
Source File: CollectionLoggingTest.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Test
public void testAvailableCharsets() throws SocketException {
    final Logger logger = context.getLogger(CollectionLoggingTest.class.getName());
    logger.error(Charset.availableCharsets());
    // TODO: some assertions
}
 
Example 19
Source File: AbstractJdbcAppenderFactoryMethodTest.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Test
public void testFactoryMethodConfig() throws Exception {
    try (final Connection connection = jdbcRule.getConnectionSource().getConnection()) {
        final SQLException exception = new SQLException("Some other error message!");
        final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try (final PrintWriter writer = new PrintWriter(outputStream)) {
            exception.printStackTrace(writer);
        }
        final String stackTrace = outputStream.toString();

        final long millis = System.currentTimeMillis();

        ThreadContext.put("some_int", "42");
        final Logger logger = LogManager.getLogger(this.getClass().getName() + ".testFactoryMethodConfig");
        logger.debug("Factory logged message 01.");
        logger.error("Error from factory 02.", exception);

        try (final Statement statement = connection.createStatement();
                final ResultSet resultSet = statement.executeQuery("SELECT * FROM fmLogEntry ORDER BY id")) {

            assertTrue("There should be at least one row.", resultSet.next());

            long date = resultSet.getTimestamp("eventDate").getTime();
            long anotherDate = resultSet.getTimestamp("anotherDate").getTime();
            assertEquals(date, anotherDate);
            assertTrue("The date should be later than pre-logging (1).", date >= millis);
            assertTrue("The date should be earlier than now (1).", date <= System.currentTimeMillis());
            assertEquals("The literal column is not correct (1).", "Some Other Literal Value",
                    resultSet.getString("literalColumn"));
            assertEquals("The level column is not correct (1).", "DEBUG", resultSet.getNString("level"));
            assertEquals("The logger column is not correct (1).", logger.getName(), resultSet.getNString("logger"));
            assertEquals("The message column is not correct (1).", "Factory logged message 01.",
                    resultSet.getString("message"));
            assertEquals("The exception column is not correct (1).", Strings.EMPTY,
                    IOUtils.readStringAndClose(resultSet.getNClob("exception").getCharacterStream(), -1));

            assertTrue("There should be two rows.", resultSet.next());

            date = resultSet.getTimestamp("eventDate").getTime();
            anotherDate = resultSet.getTimestamp("anotherDate").getTime();
            assertEquals(date, anotherDate);
            assertTrue("The date should be later than pre-logging (2).", date >= millis);
            assertTrue("The date should be earlier than now (2).", date <= System.currentTimeMillis());
            assertEquals("The literal column is not correct (2).", "Some Other Literal Value",
                    resultSet.getString("literalColumn"));
            assertEquals("The level column is not correct (2).", "ERROR", resultSet.getNString("level"));
            assertEquals("The logger column is not correct (2).", logger.getName(), resultSet.getNString("logger"));
            assertEquals("The message column is not correct (2).", "Error from factory 02.",
                    resultSet.getString("message"));
            assertEquals("The exception column is not correct (2).", stackTrace,
                    IOUtils.readStringAndClose(resultSet.getNClob("exception").getCharacterStream(), -1));

            assertFalse("There should not be three rows.", resultSet.next());
        }
    }
}
 
Example 20
Source File: BasicLoggingTest.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Test
public void test1() {
    final Logger logger = LogManager.getLogger(BasicLoggingTest.class.getName());
    logger.debug("debug not set");
    logger.error("Test message");
}