org.apache.logging.log4j.core.util.Throwables Java Examples

The following examples show how to use org.apache.logging.log4j.core.util.Throwables. 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: LoghubAppender.java    From aliyun-log-log4j2-appender with Apache License 2.0 6 votes vote down vote up
private String getThrowableStr(Throwable throwable) {
    if (throwable == null) {
        return null;
    }
    StringBuilder sb = new StringBuilder();
    boolean isFirst = true;
    for (String s : Throwables.toStringList(throwable)) {
        if (isFirst) {
            isFirst = false;
        } else {
            sb.append(System.getProperty("line.separator"));
        }
        sb.append(s);
    }
    return sb.toString();
}
 
Example #2
Source File: SocketAppenderTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    this.thread = Thread.currentThread();
    final byte[] bytes = new byte[4096];
    final DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
    try {
        while (!shutdown) {
            latch.countDown();
            sock.receive(packet);
            ++count;
            final LogEvent event = objectMapper.readValue(packet.getData(), Log4jLogEvent.class);
            queue.add(event);
        }
    } catch (final Throwable e) {
        e.printStackTrace();
        if (!shutdown) {
            Throwables.rethrow(e);
        }
    }
}
 
Example #3
Source File: SocketAppenderTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    try {
        try (final Socket socket = serverSocket.accept()) {
            if (socket != null) {
                final InputStream is = socket.getInputStream();
                while (!shutdown) {
                    final MappingIterator<LogEvent> mappingIterator = objectMapper.readerFor(Log4jLogEvent.class).readValues(is);
                    while (mappingIterator.hasNextValue()) {
                        queue.add(mappingIterator.nextValue());
                        ++count;
                    }
                }
            }
        }
    } catch (final EOFException eof) {
        // Socket is closed.
    } catch (final Exception e) {
        if (!shutdown) {
            Throwables.rethrow(e);
        }
    }
}
 
Example #4
Source File: MockUdpSyslogServer.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    System.out.println("Log4j UDP Server started.");
    this.thread = Thread.currentThread();
    final byte[] bytes = new byte[4096];
    final DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
    try {
        while (!shutdown) {
            socket.receive(packet);
            final String str = new String(packet.getData(), 0, packet.getLength());
            messageList.add(str);
        }
    } catch (final Exception e) {
        if (!shutdown) {
            Throwables.rethrow(e);
        }
    }
    System.out.println("Log4j UDP server stopped.");
}
 
Example #5
Source File: TestClassLoader.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Override
protected Class<?> findClass(final String name) throws ClassNotFoundException {
    final String path = name.replace('.', '/').concat(".class");
    final URL resource = super.getResource(path);
    if (resource == null) {
        throw new ClassNotFoundException(name);
    }
    try {
        final URLConnection uc = resource.openConnection();
        final int len = uc.getContentLength();
        final InputStream in = new BufferedInputStream(uc.getInputStream());
        final byte[] bytecode = new byte[len];
        try {
            IOUtils.readFully(in, bytecode);
        } finally {
            Closer.closeSilently(in);
        }
        return defineClass(name, bytecode, 0, bytecode.length);
    } catch (final IOException e) {
        Throwables.rethrow(e);
        return null; // unreachable
    }
}
 
Example #6
Source File: JdbcAppenderMapMessageDataSourceTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private DataSource createMockDataSource() {
    try {
        final DataSource dataSource = mock(DataSource.class);
        given(dataSource.getConnection()).willAnswer(new Answer<Connection>() {
            @Override
            public Connection answer(final InvocationOnMock invocation) throws Throwable {
                return jdbcRule.getConnectionSource().getConnection();
            }
        });
        return dataSource;
    } catch (final SQLException e) {
        Throwables.rethrow(e);
        throw new InternalError("unreachable");
    }
}
 
Example #7
Source File: Log4j2SimpleLogEvent.java    From flogger with Apache License 2.0 5 votes vote down vote up
LogEvent asLoggingEvent() {
  // The Mapped Diagnostic Context (MDC) allows to include additional metadata into logs which
  // are written from the current thread.
  //
  // Example:
  //  MDC.put("user.id", userId);
  //  // do business logic that triggers logs
  //  MDC.clear();
  //
  // By using '%X{key}' in the ConversionPattern of an appender this data can be included in the
  // logs.
  //
  // We could include this data here by doing 'MDC.getContext()', but we don't want to encourage
  // people using the log4j specific MDC. Instead this should be supported by a LoggingContext and
  // usage of Flogger tags.
  Map<String, String> mdcProperties = Collections.emptyMap();

  // The fully qualified class name of the logger instance is normally used to compute the log
  // location (file, class, method, line number) from the stacktrace. Since we already have the
  // log location in hand we don't need this computation. By passing in null as fully qualified
  // class name of the logger instance we ensure that the log location computation is disabled.
  // this is important since the log location computation is very expensive.
  return Log4jLogEvent.newBuilder()
      .setLoggerName(logger.toString())
      .setLoggerFqcn(null)
      .setLevel(level)
      .setMessage(new SimpleMessage(message))
      .setThreadName(Thread.currentThread().getName())
      // Don't use Duration here as (a) it allocates and (b) we can't allow error on overflow.
      .setTimeMillis(TimeUnit.NANOSECONDS.toMillis(logData.getTimestampNanos()))
      .setThrown(thrown != null ? Throwables.getRootCause(thrown) : null)
      .setIncludeLocation(true)
      .setSource(getLocationInfo())
      .setContextMap(mdcProperties)
      .build();
}
 
Example #8
Source File: AbstractJdbcAppenderDataSourceTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private DataSource createMockDataSource() {
    try {
        final DataSource dataSource = mock(DataSource.class);
        given(dataSource.getConnection()).willAnswer(new Answer<Connection>() {
            @Override
            public Connection answer(final InvocationOnMock invocation) throws Throwable {
                return jdbcRule.getConnectionSource().getConnection();
            }
        });
        return dataSource;
    } catch (final SQLException e) {
        Throwables.rethrow(e);
        throw new InternalError("unreachable");
    }
}
 
Example #9
Source File: FileAppenderTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) {

            if (args.length != 3) {
                System.out.println("Required arguments 'id', 'count' and 'lock' not provided");
                System.exit(-1);
            }
            final String id = args[0];

            final int count = Integer.parseInt(args[1]);

            if (count <= 0) {
                System.out.println("Invalid count value: " + args[1]);
                System.exit(-1);
            }
            final boolean lock = Boolean.parseBoolean(args[2]);

            final boolean createOnDemand = Boolean.parseBoolean(args[2]);

            // System.out.println("Got arguments " + id + ", " + count + ", " + lock);

            try {
                writer(lock, count, id, createOnDemand, true);
                // thread.sleep(50);

            } catch (final Exception e) {
                Throwables.rethrow(e);
            }

        }
 
Example #10
Source File: FileAppenderTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    final Thread thread = Thread.currentThread();

    try {
        writer(lock, logEventCount, thread.getName(), createOnDemand, true);
    } catch (final Exception e) {
        exceptionRef[0] = e;
        Throwables.rethrow(e);
    }
}
 
Example #11
Source File: CompositeConfigurationTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private void runTest(final LoggerContextRule rule, final Statement statement) {
    try {
        rule.apply(statement, Description
                .createTestDescription(getClass(), Thread.currentThread().getStackTrace()[1].getMethodName()))
                .evaluate();
    } catch (final Throwable e) {
        Throwables.rethrow(e);
    }
}
 
Example #12
Source File: AsyncLoggerConfigDisruptor.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public void enqueueEvent(final LogEvent event, final AsyncLoggerConfig asyncLoggerConfig) {
    // LOG4J2-639: catch NPE if disruptor field was set to null after our check above
    try {
        final LogEvent logEvent = prepareEvent(event);
        enqueue(logEvent, asyncLoggerConfig);
    } catch (final NullPointerException npe) {
        // Note: NPE prevents us from adding a log event to the disruptor after it was shut down,
        // which could cause the publishEvent method to hang and never return.
        LOGGER.warn("Ignoring log event after log4j was shut down: {} [{}] {}", event.getLevel(),
                event.getLoggerName(), event.getMessage().getFormattedMessage()
                        + (event.getThrown() == null ? "" : Throwables.toStringList(event.getThrown())));
    }
}
 
Example #13
Source File: DefaultConfigurationBuilder.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public String toXmlConfiguration() {
    final StringWriter sw = new StringWriter();
    try {
        final XMLStreamWriter xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(sw);
        writeXmlConfiguration(xmlWriter);
        xmlWriter.close();
    } catch (final XMLStreamException e) {
        Throwables.rethrow(e);
    }
    return sw.toString();
}
 
Example #14
Source File: DefaultConfigurationBuilder.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public void writeXmlConfiguration(final OutputStream output) throws IOException {
    try {
        final XMLStreamWriter xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(output);
        writeXmlConfiguration(xmlWriter);
        xmlWriter.close();
    } catch (final XMLStreamException e) {
        if (e.getNestedException() instanceof IOException) {
            throw (IOException)e.getNestedException();
        }
        Throwables.rethrow(e);
    }
}
 
Example #15
Source File: FastDatePrinter.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * <p>Performs the formatting by applying the rules to the
 * specified calendar.</p>
 *
 * @param calendar  the calendar to format
 * @param buf  the buffer to format into
 * @param <B> the Appendable class type, usually StringBuilder or StringBuffer.
 * @return the specified string buffer
 */
private <B extends Appendable> B applyRules(final Calendar calendar, final B buf) {
    try {
        for (final Rule rule : mRules) {
            rule.appendTo(buf, calendar);
        }
    } catch (final IOException ioe) {
        Throwables.rethrow(ioe);
    }
    return buf;
}
 
Example #16
Source File: ExceptionRootCauseResolver.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
EventResolver createStackTraceObjectResolver(EventResolverContext context) {
    return (final LogEvent logEvent, final JsonWriter jsonWriter) -> {
        final Throwable exception = logEvent.getThrown();
        if (exception == null) {
            jsonWriter.writeNull();
        } else {
            final Throwable rootCause = Throwables.getRootCause(exception);
            context.getStackTraceObjectResolver().resolve(rootCause, jsonWriter);
        }
    };
}
 
Example #17
Source File: ExceptionRootCauseResolver.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
EventResolver createStackTraceStringResolver(final EventResolverContext context) {
    final StackTraceStringResolver stackTraceStringResolver =
            new StackTraceStringResolver(context);
    return (final LogEvent logEvent, final JsonWriter jsonWriter) -> {
        final Throwable exception = logEvent.getThrown();
        if (exception == null) {
            jsonWriter.writeNull();
        } else {
            final Throwable rootCause = Throwables.getRootCause(exception);
            stackTraceStringResolver.resolve(rootCause, jsonWriter);
        }
    };
}
 
Example #18
Source File: ExceptionRootCauseResolver.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
EventResolver createMessageResolver(final EventResolverContext context) {
    return (final LogEvent logEvent, final JsonWriter jsonWriter) -> {
        final Throwable exception = logEvent.getThrown();
        if (exception == null) {
            jsonWriter.writeNull();
        } else {
            final Throwable rootCause = Throwables.getRootCause(exception);
            final String rootCauseMessage = rootCause.getMessage();
            jsonWriter.writeString(rootCauseMessage);
        }
    };
}
 
Example #19
Source File: ExceptionRootCauseResolver.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
EventResolver createClassNameResolver() {
    return (final LogEvent logEvent, final JsonWriter jsonWriter) -> {
        final Throwable exception = logEvent.getThrown();
        if (exception == null) {
            jsonWriter.writeNull();
        } else {
            final Throwable rootCause = Throwables.getRootCause(exception);
            final String rootCauseClassName = rootCause.getClass().getCanonicalName();
            jsonWriter.writeString(rootCauseClassName);
        }
    };
}
 
Example #20
Source File: LogEventAdapter.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 Return this event's throwable's string[] representaion.
 */
@Override
public
String[] getThrowableStrRep() {
    if (event.getThrown() != null) {
        return Throwables.toStringList(event.getThrown()).toArray(new String[0]);
    }
    return null;
}
 
Example #21
Source File: LogEventAdapter.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * Return this event's throwable's string[] representaion.
 */
@Override
public String[] getThrowableStrRep() {
    if (event.getThrown() != null) {
        return Throwables.toStringList(event.getThrown()).toArray(new String[0]);
    }
    return null;
}
 
Example #22
Source File: AsyncLoggerDisruptor.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
private void logWarningOnNpeFromDisruptorPublish(
        final Level level, final String fqcn, final Message msg, final Throwable thrown) {
    LOGGER.warn("[{}] Ignoring log event after log4j was shut down: {} [{}] {}{}", contextName,
            level, fqcn, msg.getFormattedMessage(), thrown == null ? "" : Throwables.toStringList(thrown));
}