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

项目:log4j2    文件:Log4jTaglibLoggerContext.java   
@Override
public Log4jTaglibLogger getLogger(final String name, final MessageFactory factory) {
    Log4jTaglibLogger logger = this.loggers.get(name);
    if (logger != null) {
        AbstractLogger.checkMessageFactory(logger, factory);
        return logger;
    }

    synchronized (this.loggers) {
        logger = this.loggers.get(name);
        if (logger == null) {
            final Logger original = factory == null ?
                    LogManager.getLogger(name) : LogManager.getLogger(name, factory);
            if (!(original instanceof AbstractLogger)) {
                throw new LoggingException(
                        "Log4j Tag Library requires base logging system to extend Log4j AbstractLogger."
                );
            }
            // wrap a logger from an underlying implementation
            logger = new Log4jTaglibLogger((AbstractLogger) original, name, original.getMessageFactory());
            this.loggers.put(name, logger);
        }
    }

    return logger;
}
项目: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 {
            final GZIPOutputStream os = new GZIPOutputStream(baos);
            os.write(body);
            os.close();
        } catch (final IOException ioe) {
            throw new LoggingException("Unable to compress message", ioe);
        }
        super.setBody(baos.toByteArray());
    } else {
        super.setBody(body);
    }
}
项目: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;
        } else {
            throw new LoggingException("Unable to write to failover appenders", failoverException);
        }
    }
}
项目:log4j2    文件:SocketAppenderTest.java   
@Test
public void testTCPAppender() throws Exception {

    final SocketAppender appender = SocketAppender.createAppender("localhost", PORT, "tcp", "-1",
        "false", "Test", null, null, null, null, null, null);
    appender.start();

    // set appender on root and set level to debug
    root.addAppender(appender);
    root.setAdditive(false);
    root.setLevel(Level.DEBUG);
    root.debug("This is a test message");
    final Throwable child = new LoggingException("This is a test");
    root.error("Throwing an exception", child);
    root.debug("This is another test message");
    Thread.sleep(250);
    LogEvent event = list.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", tcpCount > 0);
    event = list.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", tcpCount > 1);
}
项目: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);
    }
}
项目: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);
    }
}
项目: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);
    }
}
项目:logging-log4j2    文件:SerializedLayoutTest.java   
@Test
public void testSerialization() throws Exception {
    final SerializedLayout layout = SerializedLayout.createLayout();
    final Throwable throwable = new LoggingException("Test");
    final LogEvent event = Log4jLogEvent.newBuilder() //
            .setLoggerName(this.getClass().getName()) //
            .setLoggerFqcn("org.apache.logging.log4j.core.Logger") //
            .setLevel(Level.INFO) //
            .setMessage(new SimpleMessage("Hello, world!")) //
            .setThrown(throwable) //
            .build();
    final byte[] result = layout.toByteArray(event);
    assertNotNull(result);
    final FileOutputStream fos = new FileOutputStream(DAT_PATH);
    fos.write(layout.getHeader());
    fos.write(result);
    fos.close();
}
项目:wolfarmor    文件:LogHelper.java   
/**
 * Log a message to the mod logger at the specified level
 *
 * @param level   The level of the message
 * @param message The message
 */
@SuppressWarnings("WeakerAccess")
public void log(@Nonnull Level level, @Nonnull String message) {
    if (logger == null) {
        throw new LoggingException("Logger has not been initialized");
    }

    logger.log(level, message);
}
项目: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);
    }
}
项目: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);
        }
    }
}
项目:log4j2    文件:FailOnceAppender.java   
@Override
public void append(final LogEvent event) {
    if (fail) {
        fail = false;
        throw new LoggingException("Always fail");
    } else {
        events.add(event);
    }
}
项目: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);
    Thread.sleep(100);
    final List<String> list = app.getMessages();
    assertNotNull("No events generated", list);
    assertTrue("Incorrect number of events. Expected 1, got " + list.size(), list.size() == 1);
    final String msg = list.get(0);
    assertTrue("No parent exception", msg.contains("java.lang.IllegalStateException"));
}
项目:logging-log4j2    文件:AbstractLogger.java   
private void handleLogMessageException(final Exception exception, final String fqcn, final Message msg) {
    if (exception instanceof LoggingException) {
        throw (LoggingException) exception;
    }
    final String format = msg.getFormat();
    final StringBuilder sb = new StringBuilder(format.length() + 100);
    sb.append(fqcn);
    sb.append(" caught ");
    sb.append(exception.getClass().getName());
    sb.append(" logging ");
    sb.append(msg.getClass().getSimpleName());
    sb.append(": ");
    sb.append(format);
    StatusLogger.getLogger().warn(sb.toString(), exception);
}
项目: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();
}
项目: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);
    }
}
项目: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);
    }
}
项目: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);
    }
}
项目:logging-log4j2    文件:AbstractRolloverStrategy.java   
protected SortedMap<Integer, Path> getEligibleFiles(final String path, final String logfilePattern, final boolean isAscending) {
    final TreeMap<Integer, Path> eligibleFiles = new TreeMap<>();
    final File file = new File(path);
    File parent = file.getParentFile();
    if (parent == null) {
        parent = new File(".");
    } else {
        parent.mkdirs();
    }
    if (!logfilePattern.contains("%i")) {
        return eligibleFiles;
    }
    final Path dir = parent.toPath();
    String fileName = file.getName();
    final int suffixLength = suffixLength(fileName);
    if (suffixLength > 0) {
        fileName = fileName.substring(0, fileName.length() - suffixLength) + ".*";
    }
    final String filePattern = fileName.replace(NotANumber.VALUE, "(\\d+)");
    final Pattern pattern = Pattern.compile(filePattern);

    try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
        for (final Path entry: stream) {
            final Matcher matcher = pattern.matcher(entry.toFile().getName());
            if (matcher.matches()) {
                final Integer index = Integer.parseInt(matcher.group(1));
                eligibleFiles.put(index, entry);
            }
        }
    } catch (final IOException ioe) {
        throw new LoggingException("Error reading folder " + dir + " " + ioe.getMessage(), ioe);
    }
    return isAscending? eligibleFiles : eligibleFiles.descendingMap();
}
项目: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);
        }
    }
}
项目:logging-log4j2    文件:FailOnceAppender.java   
@Override
public void append(final LogEvent event) {
    if (fail) {
        fail = false;
        throw new LoggingException("Always fail");
    }
    events.add(event);
}
项目: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"));
}
项目: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));
        boolean interrupted = false;
        int count = 0;
        do {
            try {
                future.get();
            } catch (final InterruptedException ie) {
                interrupted = true;
                ++count;
            }
        } while (interrupted && count <= 1);

    } catch (final Exception ex) {
        throw new LoggingException("Exception occurred writing log event", ex);
    }
}
项目:log4j2    文件:AlwaysFailAppender.java   
@Override
public void append(final LogEvent event) {
    throw new LoggingException("Always fail");
}
项目:log4j2    文件:SerializedLayoutTest.java   
/**
 * Test case for MDC conversion pattern.
 */
@Test
public void testLayout() throws Exception {

    // set up appender
    final SerializedLayout layout = SerializedLayout.createLayout();
    final ListAppender appender = new ListAppender("List", null, layout, false, true);
    appender.start();

    // set appender on root and set level to debug
    root.addAppender(appender);
    root.setLevel(Level.DEBUG);

    // output starting message
    root.debug("starting mdc pattern test");

    root.debug("empty mdc");

    ThreadContext.put("key1", "value1");
    ThreadContext.put("key2", "value2");

    root.debug("filled mdc");

    ThreadContext.remove("key1");
    ThreadContext.remove("key2");

    root.error("finished mdc pattern test", new NullPointerException("test"));

    final Exception parent = new IllegalStateException("Test");
    final Throwable child = new LoggingException("This is a test", parent);

    root.error("Throwing an exception", child);

    appender.stop();

    final List<byte[]> data = appender.getData();
    assertTrue(data.size() > 0);
    int i = 0;
    for (final byte[] item : data) {
        final ByteArrayInputStream bais = new ByteArrayInputStream(item);
        final ObjectInputStream ois = new ObjectInputStream(bais);
        LogEvent event;
        try {
            event = (LogEvent) ois.readObject();
        } catch (final IOException ioe) {
            System.err.println("Exception processing item " + i);
            throw ioe;
        }
        assertTrue("Incorrect event", event.toString().equals(expected[i]));
        ++i;
    }

}
项目: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));
        boolean interrupted = false;
        int ieCount = 0;
        do {
            try {
                future.get();
            } catch (final InterruptedException ie) {
                interrupted = true;
                ++ieCount;
            }
        } while (interrupted && ieCount <= 1);

    } catch (final Exception ex) {
        throw new LoggingException("Exception occurred writing log event", ex);
    }
}
项目:logging-log4j2    文件:AlwaysFailAppender.java   
@Override
public void append(final LogEvent event) {
    throw new LoggingException("Always fail");
}
项目:logging-log4j2    文件:DeadlockAppender.java   
@Override
public void append(final LogEvent event) {
    throw new LoggingException("Always fail");
}
项目: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()
            .withHost("localhost")
            .withPort(tcpTestServer.getLocalPort())
            .withReconnectDelayMillis(-1)
            .withName("test")
            .withImmediateFail(false)
            .withBufferSize(bufferSize)
            .withLayout(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());
}