下面列出了怎么用org.apache.logging.log4j.core.util.Throwables的API类实例代码及写法,或者点击链接到github查看源代码。
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();
}
@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);
}
}
}
@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);
}
}
}
@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
}
}
@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.");
}
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();
}
/**
* 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;
}
/**
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;
}
@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);
}
};
}
@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);
}
};
}
@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);
}
};
}
@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);
}
};
}
/**
* <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;
}
@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);
}
}
@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();
}
@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())));
}
}
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);
}
}
@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);
}
}
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);
}
}
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");
}
}
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");
}
}
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));
}