类org.apache.logging.log4j.LoggingException源码实例Demo

下面列出了怎么用org.apache.logging.log4j.LoggingException的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: logging-log4j-audit   文件: TransferTest.java
@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);
}
 
源代码2 项目: logging-log4j2   文件: SmtpManager.java
/**
 * 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);
    }
}
 
源代码3 项目: logging-log4j2   文件: FlumeEvent.java
/**
 * 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);
    }
}
 
源代码4 项目: logging-log4j2   文件: FailoverAppender.java
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);
    }
}
 
源代码5 项目: logging-log4j-audit   文件: TransferTest.java
@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);
    }
}
 
源代码6 项目: logging-log4j2   文件: AbstractLogger.java
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);
}
 
源代码7 项目: logging-log4j2   文件: CassandraRule.java
@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();
}
 
源代码8 项目: logging-log4j2   文件: OverflowTest.java
@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");
	}
}
 
源代码9 项目: logging-log4j2   文件: PluginProcessor.java
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);
    }
}
 
源代码10 项目: logging-log4j2   文件: TagUtils.java
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);
    }
}
 
源代码11 项目: logging-log4j2   文件: IoBuilder.java
/**
 * 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);
    }
}
 
源代码12 项目: logging-log4j2   文件: OverflowTest.java
@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");
	}
}
 
源代码13 项目: logging-log4j2   文件: FlumeEmbeddedManager.java
@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);
    }
}
 
源代码14 项目: logging-log4j2   文件: FlumePersistentManager.java
@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);
    }
}
 
源代码15 项目: logging-log4j2   文件: Rfc5424Layout.java
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);
        }
    }
}
 
源代码16 项目: logging-log4j2   文件: FailOnceAppender.java
@Override
public void append(final LogEvent event) {
    if (fail) {
        fail = false;
        throw new LoggingException("Always fail");
    }
    events.add(event);
}
 
源代码17 项目: logging-log4j2   文件: AsyncAppenderTest.java
@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"));
}
 
源代码18 项目: logging-log4j2   文件: SocketAppenderTest.java
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());
}
 
源代码19 项目: logging-log4j2   文件: Log4jLoggerFactory.java
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;
}
 
源代码20 项目: logging-log4j2   文件: Log4jLoggerFactory.java
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;
}
 
源代码21 项目: logging-log4j2   文件: AlwaysFailAppender.java
@Override
public void append(final LogEvent event) {
    throw new LoggingException("Always fail");
}
 
源代码22 项目: logging-log4j2   文件: DeadlockAppender.java
@Override
public void append(final LogEvent event) {
    throw new LoggingException("Always fail");
}
 
 类所在包
 同包方法