Java源码示例:org.apache.logging.log4j.LoggingException
示例1
@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
/**
* 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
/**
* 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
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
@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
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
@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
@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
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
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
/**
* 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
@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
@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
@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
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
@Override
public void append(final LogEvent event) {
if (fail) {
fail = false;
throw new LoggingException("Always fail");
}
events.add(event);
}
示例17
@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
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
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
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
@Override
public void append(final LogEvent event) {
throw new LoggingException("Always fail");
}
示例22
@Override
public void append(final LogEvent event) {
throw new LoggingException("Always fail");
}