Search in sources :

Example 6 with LoggingException

use of org.apache.logging.log4j.LoggingException in project logging-log4j2 by apache.

the class AbstractRolloverStrategy method getEligibleFiles.

protected SortedMap<Integer, Path> getEligibleFiles(String path, String logfilePattern, boolean isAscending) {
    TreeMap<Integer, Path> eligibleFiles = new TreeMap<>();
    File file = new File(path);
    File parent = file.getParentFile();
    if (parent == null) {
        parent = new File(".");
    } else {
        parent.mkdirs();
    }
    if (!logfilePattern.contains("%i")) {
        return eligibleFiles;
    }
    Path dir = parent.toPath();
    String fileName = file.getName();
    int suffixLength = suffixLength(fileName);
    if (suffixLength > 0) {
        fileName = fileName.substring(0, fileName.length() - suffixLength) + ".*";
    }
    String filePattern = fileName.replace(NotANumber.VALUE, "(\\d+)");
    Pattern pattern = Pattern.compile(filePattern);
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
        for (Path entry : stream) {
            Matcher matcher = pattern.matcher(entry.toFile().getName());
            if (matcher.matches()) {
                Integer index = Integer.parseInt(matcher.group(1));
                eligibleFiles.put(index, entry);
            }
        }
    } catch (IOException ioe) {
        throw new LoggingException("Error reading folder " + dir + " " + ioe.getMessage(), ioe);
    }
    return isAscending ? eligibleFiles : eligibleFiles.descendingMap();
}
Also used : Path(java.nio.file.Path) Pattern(java.util.regex.Pattern) LoggingException(org.apache.logging.log4j.LoggingException) Matcher(java.util.regex.Matcher) IOException(java.io.IOException) TreeMap(java.util.TreeMap) File(java.io.File)

Example 7 with LoggingException

use of org.apache.logging.log4j.LoggingException in project logging-log4j2 by apache.

the class SerializedLayoutTest method testLayout.

/**
     * Test case for MDC conversion pattern.
     */
@Test
public void testLayout() throws Exception {
    final Map<String, Appender> appenders = root.getAppenders();
    for (final Appender appender : appenders.values()) {
        root.removeAppender(appender);
    }
    // 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;
    }
    for (final Appender app : appenders.values()) {
        root.addAppender(app);
    }
}
Also used : Appender(org.apache.logging.log4j.core.Appender) ListAppender(org.apache.logging.log4j.test.appender.ListAppender) LoggingException(org.apache.logging.log4j.LoggingException) LogEvent(org.apache.logging.log4j.core.LogEvent) Log4jLogEvent(org.apache.logging.log4j.core.impl.Log4jLogEvent) IOException(java.io.IOException) LoggingException(org.apache.logging.log4j.LoggingException) IOException(java.io.IOException) ByteArrayInputStream(java.io.ByteArrayInputStream) ListAppender(org.apache.logging.log4j.test.appender.ListAppender) ObjectInputStream(java.io.ObjectInputStream) Test(org.junit.Test)

Example 8 with LoggingException

use of org.apache.logging.log4j.LoggingException in project logging-log4j2 by apache.

the class SerializedLayoutTest method testSerialization.

@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();
}
Also used : LoggingException(org.apache.logging.log4j.LoggingException) LogEvent(org.apache.logging.log4j.core.LogEvent) Log4jLogEvent(org.apache.logging.log4j.core.impl.Log4jLogEvent) SimpleMessage(org.apache.logging.log4j.message.SimpleMessage) FileOutputStream(java.io.FileOutputStream) Test(org.junit.Test)

Example 9 with LoggingException

use of org.apache.logging.log4j.LoggingException in project logging-log4j2 by apache.

the class SmtpManager method sendEvents.

/**
     * 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);
    }
}
Also used : InternetHeaders(javax.mail.internet.InternetHeaders) LoggingException(org.apache.logging.log4j.LoggingException) LogEvent(org.apache.logging.log4j.core.LogEvent) Log4jLogEvent(org.apache.logging.log4j.core.impl.Log4jLogEvent) MutableLogEvent(org.apache.logging.log4j.core.impl.MutableLogEvent) MimeMultipart(javax.mail.internet.MimeMultipart) MessagingException(javax.mail.MessagingException) IOException(java.io.IOException)

Example 10 with LoggingException

use of org.apache.logging.log4j.LoggingException in project logging-log4j2 by apache.

the class AsyncAppenderTest method testException.

@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"));
}
Also used : LoggingException(org.apache.logging.log4j.LoggingException) TimeUnit(java.util.concurrent.TimeUnit) Logger(org.apache.logging.log4j.Logger) LoggingException(org.apache.logging.log4j.LoggingException) Test(org.junit.Test)

Aggregations

LoggingException (org.apache.logging.log4j.LoggingException)10 IOException (java.io.IOException)5 LogEvent (org.apache.logging.log4j.core.LogEvent)4 Log4jLogEvent (org.apache.logging.log4j.core.impl.Log4jLogEvent)4 Test (org.junit.Test)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 ObjectInputStream (java.io.ObjectInputStream)2 SimpleMessage (org.apache.logging.log4j.message.SimpleMessage)2 LockConflictException (com.sleepycat.je.LockConflictException)1 DataOutputStream (java.io.DataOutputStream)1 File (java.io.File)1 FileOutputStream (java.io.FileOutputStream)1 ObjectOutputStream (java.io.ObjectOutputStream)1 Path (java.nio.file.Path)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 TreeMap (java.util.TreeMap)1 TimeUnit (java.util.concurrent.TimeUnit)1 Matcher (java.util.regex.Matcher)1