org.apache.logging.log4j.LoggingException Java Examples

The following examples show how to use org.apache.logging.log4j.LoggingException. 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: TransferTest.java    From logging-log4j-audit with Apache License 2.0 6 votes vote down vote up
@Test
public void testCustomExceptionHandlerIsPassedToEvent() {
    AbstractConfiguration config = setUpFailingAppender();

    MutableBoolean exceptionHandled = new MutableBoolean(false);
 LogEventFactory.setDefaultHandler((message, ex) -> {
     assertThat(ex, instanceOf(LoggingException.class));
     exceptionHandled.setTrue();
 });

    Transfer transfer = setUpMinimumEvent();
    transfer.logEvent();

    assertTrue("Exception was not handled through the custom handler", exceptionHandled.isTrue());

    config.removeAppender(failingAppenderName);
}
 
Example #2
Source File: SmtpManager.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * Send the contents of the cyclic buffer as an e-mail message.
 * @param layout The layout for formatting the events.
 * @param appendEvent The event that triggered the send.
 */
public void sendEvents(final Layout<?> layout, final LogEvent appendEvent) {
    if (message == null) {
        connect(appendEvent);
    }
    try {
        final LogEvent[] priorEvents = buffer.removeAll();
        // LOG4J-310: log appendEvent even if priorEvents is empty

        final byte[] rawBytes = formatContentToBytes(priorEvents, appendEvent, layout);

        final String contentType = layout.getContentType();
        final String encoding = getEncoding(rawBytes, contentType);
        final byte[] encodedBytes = encodeContentToBytes(rawBytes, encoding);

        final InternetHeaders headers = getHeaders(contentType, encoding);
        final MimeMultipart mp = getMimeMultipart(encodedBytes, headers);

        sendMultipartMessage(message, mp);
    } catch (final MessagingException | IOException | RuntimeException e) {
        logError("Caught exception while sending e-mail notification.", e);
        throw new LoggingException("Error occurred while sending email", e);
    }
}
 
Example #3
Source File: FailoverAppender.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private void failover(final LogEvent event, final Exception ex) {
    final RuntimeException re = ex != null ?
            (ex instanceof LoggingException ? (LoggingException) ex : new LoggingException(ex)) : null;
    boolean written = false;
    Exception failoverException = null;
    for (final AppenderControl control : failoverAppenders) {
        try {
            control.callAppender(event);
            written = true;
            break;
        } catch (final Exception fex) {
            if (failoverException == null) {
                failoverException = fex;
            }
        }
    }
    if (!written && !ignoreExceptions()) {
        if (re != null) {
            throw re;
        }
        throw new LoggingException("Unable to write to failover appenders", failoverException);
    }
}
 
Example #4
Source File: FlumeEvent.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * Set the body in the event.
 * @param body The body to add to the event.
 */
@Override
public void setBody(final byte[] body) {
    if (body == null || body.length == 0) {
        super.setBody(new byte[0]);
        return;
    }
    if (compress) {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try (GZIPOutputStream os = new GZIPOutputStream(baos)) {
            os.write(body);
        } catch (final IOException ioe) {
            throw new LoggingException("Unable to compress message", ioe);
        }
        super.setBody(baos.toByteArray());
    } else {
        super.setBody(body);
    }
}
 
Example #5
Source File: AsyncAppenderTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testException() throws Exception {
    final Logger logger = LogManager.getLogger(AsyncAppender.class);
    final Exception parent = new IllegalStateException("Test");
    final Throwable child = new LoggingException("This is a test", parent);
    logger.error("This is a test", child);
    final long timeoutMillis = TIMEOUT_MILLIS;
    final TimeUnit timeUnit = TimeUnit.MILLISECONDS;
    final List<String> list = listAppender.getMessages(1, timeoutMillis, timeUnit);
    assertNotNull("No events generated", list);
    assertTrue("Incorrect number of events after " + timeoutMillis + " " + timeUnit + ". Expected 1, got "
            + list.size(), list.size() == 1);
    final String msg = list.get(0);
    assertTrue("No parent exception", msg.contains("java.lang.IllegalStateException"));
}
 
Example #6
Source File: TransferTest.java    From logging-log4j-audit with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefaultExceptionHandlerIsInvokedOnEventLogFailure() {
    AbstractConfiguration config = setUpFailingAppender();

    exception.expect(AuditException.class);
    exception.expectCause(isA(LoggingException.class));
    exception.expectMessage("Error logging event transfer");

    Transfer transfer = setUpMinimumEvent();
    try {
        transfer.logEvent();
    } finally {
        config.removeAppender(failingAppenderName);
    }
}
 
Example #7
Source File: FailOnceAppender.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public void append(final LogEvent event) {
    if (fail) {
        fail = false;
        throw new LoggingException("Always fail");
    }
    events.add(event);
}
 
Example #8
Source File: Rfc5424Layout.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private void checkRequired(final Map<String, String> map) {
    for (final String key : mdcRequired) {
        final String value = map.get(key);
        if (value == null) {
            throw new LoggingException("Required key " + key + " is missing from the " + mdcId);
        }
    }
}
 
Example #9
Source File: FlumePersistentManager.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public void send(final Event event)  {
    if (worker.isShutdown()) {
        throw new LoggingException("Unable to record event");
    }

    final Map<String, String> headers = event.getHeaders();
    final byte[] keyData = headers.get(FlumeEvent.GUID).getBytes(UTF8);
    try {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final DataOutputStream daos = new DataOutputStream(baos);
        daos.writeInt(event.getBody().length);
        daos.write(event.getBody(), 0, event.getBody().length);
        daos.writeInt(event.getHeaders().size());
        for (final Map.Entry<String, String> entry : headers.entrySet()) {
            daos.writeUTF(entry.getKey());
            daos.writeUTF(entry.getValue());
        }
        byte[] eventData = baos.toByteArray();
        if (secretKey != null) {
            final Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            eventData = cipher.doFinal(eventData);
        }
        final Future<Integer> future = threadPool.submit(new BDBWriter(keyData, eventData, environment, database,
            gate, dbCount, getBatchSize(), lockTimeoutRetryCount));
        try {
        	future.get();
        } catch (final InterruptedException ie) {
        	// preserve interruption status
        	Thread.currentThread().interrupt();
        }
    } catch (final Exception ex) {
        throw new LoggingException("Exception occurred writing log event", ex);
    }
}
 
Example #10
Source File: FlumeEmbeddedManager.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public void send(final Event event) {
    try {
        agent.put(event);
    } catch (final EventDeliveryException ex) {
        throw new LoggingException("Unable to deliver event to Flume Appender " + shortName, ex);
    }
}
 
Example #11
Source File: OverflowTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void log() {
	try {
		final Logger logger = LoggerFactory.getLogger(OverflowTest.class);
		fail("Failed to detect inclusion of log4j-to-slf4j");
	} catch (LoggingException ex) {
		// Expected exception.
	} catch (StackOverflowError error) {
		fail("Failed to detect inclusion of log4j-to-slf4j, caught StackOverflowError");
	}
}
 
Example #12
Source File: IoBuilder.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * Builds a new {@link PrintStream} that is backed by a Logger and optionally writes to another OutputStream as
 * well. If no OutputStream is configured for this builder, then the returned PrintStream will only write to its
 * underlying Logger.
 *
 * @return a new PrintStream that optionally writes to another OutputStream in addition to its underlying Logger
 * @throws LoggingException if the configured character set is unsupported by {@link PrintStream}
 */
public PrintStream buildPrintStream() {
    try {
        if (this.outputStream == null) {
            return new LoggerPrintStream(this.logger, this.autoFlush, this.charset, this.fqcn, this.level,
                this.marker);
        }
        return new LoggerPrintStream(this.outputStream, this.autoFlush, this.charset, this.logger, this.fqcn,
            this.level, this.marker);
    } catch (final UnsupportedEncodingException e) {
        // this exception shouldn't really happen since we use Charset and not String
        throw new LoggingException(e);
    }
}
 
Example #13
Source File: TagUtils.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private static Log4jTaglibLogger getLogger(final Log4jTaglibLoggerContext context, final String name,
                                           final MessageFactory factory)
        throws JspException {
    try {
        return context.getLogger(name, factory);
    } catch (final LoggingException e) {
        throw new JspException(e.getMessage(), e);
    }
}
 
Example #14
Source File: PluginProcessor.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private PrintWriter createSourceFile(String fqcn) {
    try {
        JavaFileObject sourceFile = processingEnv.getFiler().createSourceFile(fqcn);
        return new PrintWriter(sourceFile.openWriter());
    } catch (IOException e) {
        throw new LoggingException("Unable to create Plugin Service Class " + fqcn, e);
    }
}
 
Example #15
Source File: OverflowTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void log() {
	try {
		final Logger logger = LoggerFactory.getLogger(OverflowTest.class);
		fail("Failed to detect inclusion of log4j-to-slf4j");
	} catch (LoggingException ex) {
		// Expected exception.
	} catch (StackOverflowError error) {
		fail("Failed to detect inclusion of log4j-to-slf4j, caught StackOverflowError");
	}
}
 
Example #16
Source File: CassandraRule.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    try {
        daemon.init(null);
    } catch (final IOException e) {
        throw new LoggingException("Cannot initialize embedded Cassandra instance", e);
    }
    daemon.start();
    latch.countDown();
}
 
Example #17
Source File: AbstractLogger.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private void handleLogMessageException(final Exception exception, final String fqcn, final Message msg) {
    if (exception instanceof LoggingException) {
        throw (LoggingException) exception;
    }
    StatusLogger.getLogger().warn("{} caught {} logging {}: {}", fqcn, exception.getClass().getName(),
            msg.getClass().getSimpleName(), msg.getFormat(), exception);
}
 
Example #18
Source File: Log4jLoggerFactory.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
private LoggerContext validateContext(final LoggerContext context) {
    if (TO_SLF4J_CONTEXT.equals(context.getClass().getName())) {
        throw new LoggingException("log4j-slf4j-impl cannot be present with log4j-to-slf4j");
    }
    return context;
}
 
Example #19
Source File: Log4jLoggerFactory.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
private LoggerContext validateContext(final LoggerContext context) {
    if (TO_SLF4J_CONTEXT.equals(context.getClass().getName())) {
        throw new LoggingException("log4j-slf4j-impl cannot be present with log4j-to-slf4j");
    }
    return context;
}
 
Example #20
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());
}
 
Example #21
Source File: AlwaysFailAppender.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Override
public void append(final LogEvent event) {
    throw new LoggingException("Always fail");
}
 
Example #22
Source File: DeadlockAppender.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Override
public void append(final LogEvent event) {
    throw new LoggingException("Always fail");
}