下面列出了怎么用org.apache.logging.log4j.core.impl.ThrowableProxy的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void setupModule(SetupContext context) {
super.setupModule(context);
context.setMixInAnnotations(StackTraceElement.class, StackTraceElementMixIn.class);
context.setMixInAnnotations(Marker.class, MarkerMixIn.class);
context.setMixInAnnotations(Level.class, LevelMixIn.class);
context.setMixInAnnotations(ExtendedStackTraceElement.class, ExtendedStackTraceElementMixIn.class);
context.setMixInAnnotations(ThrowableProxy.class, ThrowableProxyMixIn.class);
context.setMixInAnnotations(Message.class, MessageJacksonJsonMixIn.class);
// https://github.com/rfoltyns/log4j2-elasticsearch/issues/9, timeMillis can't be ignored
context.setMixInAnnotations(LogEvent.class, LogEventJacksonJsonMixIn.class);
}
@Override
public void append(LogEvent event) {
if (event.getLoggerName() != null && event.getLoggerName().startsWith(PACKAGE_NAME)) {
LOGGER.warn("Recursive logging from [{}] for appender [{}].", event.getLoggerName(),
getName());
return;
}
ThrowableProxy throwableProxy = event.getThrownProxy();
ThrowableWrapper rollbarThrowableWrapper = buildRollbarThrowableWrapper(throwableProxy);
Map<String, Object> custom = this.buildCustom(event);
String message = event.getMessage() != null ? event.getMessage().getFormattedMessage() : null;
Level level = this.getLevel(event);
rollbar.log(rollbarThrowableWrapper, custom, message, level, false);
}
private ThrowableWrapper buildRollbarThrowableWrapper(ThrowableProxy throwableProxy) {
if (throwableProxy == null) {
return null;
}
if (throwableProxy.getThrowable() != null) {
return new RollbarThrowableWrapper(throwableProxy.getThrowable());
}
String className = throwableProxy.getName();
String message = throwableProxy.getMessage();
ThrowableWrapper causeThrowableWrapper =
buildRollbarThrowableWrapper(throwableProxy.getCauseProxy());
StackTraceElement[] stackTraceElements = buildStackTraceElements(
throwableProxy.getStackTrace());
return new RollbarThrowableWrapper(className, message, stackTraceElements,
causeThrowableWrapper);
}
@Test
public void shouldLogEventWithAllInformationFromThrowableProxyWithThrowable() {
ThrowableWrapper throwableWrapper = new RollbarThrowableWrapper(EXCEPTION);
when(event.getLoggerName()).thenReturn(LOGGER_NAME);
when(event.getMarker()).thenReturn(marker);
when(event.getThreadName()).thenReturn(THREAD_NAME);
when(event.getLevel()).thenReturn(org.apache.logging.log4j.Level.ERROR);
when(event.getThrownProxy()).thenReturn(new ThrowableProxy(EXCEPTION));
when(event.getContextData()).thenReturn(contextData);
when(event.getContextStack()).thenReturn(contextStack);
when(event.getMessage()).thenReturn(message);
sut.append(event);
Map<String, Object> expectedCustom = buildExpectedCustom(LOGGER_NAME,
new HashMap<String, Object>(MDC), NDC, MARKER_NAME, THREAD_NAME);
verify(rollbar).log(throwableWrapper, expectedCustom, FORMATTED_MESSAGE, Level.ERROR, false);
}
@Test
public void shouldLogEventWhenNoMarker() {
RollbarThrowableWrapper throwableWrapper = new RollbarThrowableWrapper(EXCEPTION);
when(event.getLoggerName()).thenReturn(LOGGER_NAME);
when(event.getThreadName()).thenReturn(THREAD_NAME);
when(event.getLevel()).thenReturn(org.apache.logging.log4j.Level.ERROR);
when(event.getThrownProxy()).thenReturn(new ThrowableProxy(EXCEPTION));
when(event.getContextData()).thenReturn(contextData);
when(event.getContextStack()).thenReturn(contextStack);
when(event.getMessage()).thenReturn(message);
sut.append(event);
Map<String, Object> expectedCustom = buildExpectedCustom(LOGGER_NAME,
new HashMap<String, Object>(MDC), NDC, null, THREAD_NAME);
verify(rollbar).log(throwableWrapper, expectedCustom, FORMATTED_MESSAGE, Level.ERROR, false);
}
@Test
public void shouldLogEventWhenNoMDC() {
RollbarThrowableWrapper throwableWrapper = new RollbarThrowableWrapper(EXCEPTION);
when(event.getLoggerName()).thenReturn(LOGGER_NAME);
when(event.getMarker()).thenReturn(marker);
when(event.getThreadName()).thenReturn(THREAD_NAME);
when(event.getLevel()).thenReturn(org.apache.logging.log4j.Level.ERROR);
when(event.getThrownProxy()).thenReturn(new ThrowableProxy(EXCEPTION));
when(event.getContextData()).thenReturn(null);
when(event.getContextStack()).thenReturn(contextStack);
when(event.getMessage()).thenReturn(message);
sut.append(event);
Map<String, Object> expectedCustom = buildExpectedCustom(LOGGER_NAME,
null, NDC, MARKER_NAME, THREAD_NAME);
verify(rollbar).log(throwableWrapper, expectedCustom, FORMATTED_MESSAGE, Level.ERROR, false);
}
@Test
public void shouldLogEventWhenNoNDC() {
RollbarThrowableWrapper throwableWrapper = new RollbarThrowableWrapper(EXCEPTION);
when(event.getLoggerName()).thenReturn(LOGGER_NAME);
when(event.getMarker()).thenReturn(marker);
when(event.getThreadName()).thenReturn(THREAD_NAME);
when(event.getLevel()).thenReturn(org.apache.logging.log4j.Level.ERROR);
when(event.getThrownProxy()).thenReturn(new ThrowableProxy(EXCEPTION));
when(event.getContextData()).thenReturn(contextData);
when(event.getContextStack()).thenReturn(null);
when(event.getMessage()).thenReturn(message);
sut.append(event);
Map<String, Object> expectedCustom = buildExpectedCustom(LOGGER_NAME,
new HashMap<String, Object>(MDC), null, MARKER_NAME, THREAD_NAME);
verify(rollbar).log(throwableWrapper, expectedCustom, FORMATTED_MESSAGE, Level.ERROR, false);
}
public void setupModule(final SetupContext context, final boolean includeStacktrace,
final boolean stacktraceAsString) {
// JRE classes: we cannot edit those with Jackson annotations
context.setMixInAnnotations(StackTraceElement.class, StackTraceElementMixIn.class);
// Log4j API classes: we do not want to edit those with Jackson annotations because the API module should not
// depend on Jackson.
context.setMixInAnnotations(Marker.class, MarkerMixIn.class);
context.setMixInAnnotations(Level.class, LevelMixIn.class);
context.setMixInAnnotations(Instant.class, InstantMixIn.class);
context.setMixInAnnotations(LogEvent.class, LogEventJsonMixIn.class); // different ThreadContext handling
// Log4j Core classes: we do not want to bring in Jackson at runtime if we do not have to.
context.setMixInAnnotations(ExtendedStackTraceElement.class, ExtendedStackTraceElementMixIn.class);
context.setMixInAnnotations(ThrowableProxy.class, includeStacktrace
? (stacktraceAsString ? ThrowableProxyWithStacktraceAsStringMixIn.class : ThrowableProxyMixIn.class)
: ThrowableProxyWithoutStacktraceMixIn.class);
}
public void setupModule(final SetupContext context, final boolean includeStacktrace,
final boolean stacktraceAsString) {
// JRE classes: we cannot edit those with Jackson annotations
context.setMixInAnnotations(StackTraceElement.class, StackTraceElementMixIn.class);
// Log4j API classes: we do not want to edit those with Jackson annotations because the API module should not
// depend on Jackson.
context.setMixInAnnotations(Marker.class, MarkerMixIn.class);
context.setMixInAnnotations(Level.class, LevelMixIn.class);
context.setMixInAnnotations(Instant.class, InstantMixIn.class);
context.setMixInAnnotations(LogEvent.class, LogEventWithContextListMixIn.class);
// Log4j Core classes: we do not want to bring in Jackson at runtime if we do not have to.
context.setMixInAnnotations(ExtendedStackTraceElement.class, ExtendedStackTraceElementMixIn.class);
context.setMixInAnnotations(ThrowableProxy.class, includeStacktrace
? (stacktraceAsString ? ThrowableProxyWithStacktraceAsStringMixIn.class : ThrowableProxyMixIn.class)
: ThrowableProxyWithoutStacktraceMixIn.class);
}
public void setupModule(final SetupContext context, final boolean includeStacktrace,
final boolean stacktraceAsString) {
// JRE classes: we cannot edit those with Jackson annotations
context.setMixInAnnotations(StackTraceElement.class, StackTraceElementXmlMixIn.class);
// Log4j API classes: we do not want to edit those with Jackson annotations because the API module should not
// depend on Jackson.
context.setMixInAnnotations(Marker.class, MarkerXmlMixIn.class);
context.setMixInAnnotations(Level.class, LevelMixIn.class);
context.setMixInAnnotations(Instant.class, InstantXmlMixIn.class);
context.setMixInAnnotations(LogEvent.class, LogEventWithContextListXmlMixIn.class);
// Log4j Core classes: we do not want to bring in Jackson at runtime if we do not have to.
context.setMixInAnnotations(ExtendedStackTraceElement.class, ExtendedStackTraceElementXmlMixIn.class);
context.setMixInAnnotations(ThrowableProxy.class, includeStacktrace
? (stacktraceAsString ? ThrowableProxyWithStacktraceAsStringXmlMixIn.class : ThrowableProxyXmlMixIn.class)
: ThrowableProxyWithoutStacktraceXmlMixIn.class);
}
/**
* {@inheritDoc}
*/
@Override
public void format(final LogEvent event, final StringBuilder toAppendTo) {
final ThrowableProxy proxy = event.getThrownProxy();
final Throwable throwable = event.getThrown();
if ((throwable != null || proxy != null) && options.anyLines()) {
if (proxy == null) {
super.format(event, toAppendTo);
return;
}
final int len = toAppendTo.length();
if (len > 0 && !Character.isWhitespace(toAppendTo.charAt(len - 1))) {
toAppendTo.append(' ');
}
proxy.formatExtendedStackTraceTo(toAppendTo, options.getIgnorePackages(),
options.getTextRenderer(), getSuffix(event), options.getSeparator());
}
}
@Test
public void testDeserializedLogEventWithThrowableProxyButNoThrowable() {
final ExtendedThrowablePatternConverter converter = ExtendedThrowablePatternConverter.newInstance(null, null);
final Throwable originalThrowable = new Exception("something bad happened");
final ThrowableProxy throwableProxy = new ThrowableProxy(originalThrowable);
final Throwable deserializedThrowable = null;
final Log4jLogEvent event = Log4jLogEvent.newBuilder() //
.setLoggerName("testLogger") //
.setLoggerFqcn(this.getClass().getName()) //
.setLevel(Level.DEBUG) //
.setMessage(new SimpleMessage("")) //
.setThrown(deserializedThrowable) //
.setThrownProxy(throwableProxy) //
.setTimeMillis(0).build();
final StringBuilder sb = new StringBuilder();
converter.format(event, sb);
final String result = sb.toString();
assertTrue(result, result.contains(originalThrowable.getMessage()));
assertTrue(result, result.contains(originalThrowable.getStackTrace()[0].getMethodName()));
}
public void setupModule(final SetupContext context, final boolean includeStacktrace,
final boolean stacktraceAsString) {
// JRE classes: we cannot edit those with Jackson annotations
context.setMixInAnnotations(StackTraceElement.class, StackTraceElementMixIn.class);
// Log4j API classes: we do not want to edit those with Jackson annotations because the API module should not
// depend on Jackson.
context.setMixInAnnotations(Marker.class, MarkerMixIn.class);
context.setMixInAnnotations(Level.class, LevelMixIn.class);
context.setMixInAnnotations(Instant.class, InstantMixIn.class);
context.setMixInAnnotations(LogEvent.class, LogEventJsonMixIn.class); // different ThreadContext handling
// Log4j Core classes: we do not want to bring in Jackson at runtime if we do not have to.
context.setMixInAnnotations(ExtendedStackTraceElement.class, ExtendedStackTraceElementMixIn.class);
context.setMixInAnnotations(ThrowableProxy.class, includeStacktrace
? (stacktraceAsString ? ThrowableProxyWithStacktraceAsStringMixIn.class : ThrowableProxyMixIn.class)
: ThrowableProxyWithoutStacktraceMixIn.class);
}
@JsonGetter
public String getMessage() {
ThrowableProxy throwProxy = event.getThrownProxy();
if (throwProxy == null) {
return event.getMessage().getFormattedMessage();
} else {
return event.getMessage().getFormattedMessage()
+ "\n"
+ throwProxy.getExtendedStackTraceAsString();
}
}
@Test
public void shouldLogEventWithAllInformationFromThrowableProxyWithoutThrowable() {
ThrowableProxy throwableProxy = mock(ThrowableProxy.class);
when(throwableProxy.getThrowable()).thenReturn(null);
when(throwableProxy.getName()).thenReturn(EXCEPTION.getClass().getName());
when(throwableProxy.getMessage()).thenReturn(EXCEPTION.getMessage());
when(throwableProxy.getCauseProxy()).thenReturn(new ThrowableProxy(NESTED_EXCEPTION));
when(throwableProxy.getStackTrace()).thenReturn(EXCEPTION.getStackTrace());
ThrowableWrapper throwableWrapper = new RollbarThrowableWrapper(EXCEPTION.getClass().getName(),
EXCEPTION.getMessage(), EXCEPTION.getStackTrace(),
new RollbarThrowableWrapper(NESTED_EXCEPTION));
when(event.getLoggerName()).thenReturn(LOGGER_NAME);
when(event.getMarker()).thenReturn(marker);
when(event.getThreadName()).thenReturn(THREAD_NAME);
when(event.getLevel()).thenReturn(org.apache.logging.log4j.Level.ERROR);
when(event.getThrownProxy()).thenReturn(throwableProxy);
when(event.getContextData()).thenReturn(contextData);
when(event.getContextStack()).thenReturn(contextStack);
when(event.getMessage()).thenReturn(message);
sut.append(event);
Map<String, Object> expectedCustom = buildExpectedCustom(LOGGER_NAME,
new HashMap<String, Object>(MDC), NDC, MARKER_NAME, THREAD_NAME);
verify(rollbar).log(throwableWrapper, expectedCustom, FORMATTED_MESSAGE, Level.ERROR, false);
}
/**
* {@inheritDoc}
*/
@Override
public void format(final LogEvent event, final StringBuilder toAppendTo) {
final ThrowableProxy proxy = event.getThrownProxy();
final Throwable throwable = event.getThrown();
if (throwable != null && options.anyLines()) {
if (proxy == null) {
super.format(event, toAppendTo);
return;
}
final String trace = proxy.getCauseStackTraceAsString(options.getIgnorePackages(), options.getTextRenderer(), getSuffix(event), options.getSeparator());
final int len = toAppendTo.length();
if (len > 0 && !Character.isWhitespace(toAppendTo.charAt(len - 1))) {
toAppendTo.append(' ');
}
if (!options.allLines() || !Strings.LINE_SEPARATOR.equals(options.getSeparator())) {
final StringBuilder sb = new StringBuilder();
final String[] array = trace.split(Strings.LINE_SEPARATOR);
final int limit = options.minLines(array.length) - 1;
for (int i = 0; i <= limit; ++i) {
sb.append(array[i]);
if (i < limit) {
sb.append(options.getSeparator());
}
}
toAppendTo.append(sb.toString());
} else {
toAppendTo.append(trace);
}
}
}
@Test
public void testSerializationDeserialization() throws IOException, ClassNotFoundException {
final RingBufferLogEvent evt = new RingBufferLogEvent();
final String loggerName = "logger.name";
final Marker marker = null;
final String fqcn = "f.q.c.n";
final Level level = Level.TRACE;
final Message data = new SimpleMessage("message");
final Throwable t = new InternalError("not a real error");
final ContextStack contextStack = null;
final String threadName = "main";
final StackTraceElement location = null;
evt.setValues(null, loggerName, marker, fqcn, level, data, t, (StringMap) evt.getContextData(),
contextStack, -1, threadName, -1, location,
new FixedPreciseClock(12345, 678), new DummyNanoClock(1));
((StringMap) evt.getContextData()).putValue("key", "value");
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final ObjectOutputStream out = new ObjectOutputStream(baos);
out.writeObject(evt);
final ObjectInputStream in = new FilteredObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
final RingBufferLogEvent other = (RingBufferLogEvent) in.readObject();
assertEquals(loggerName, other.getLoggerName());
assertEquals(marker, other.getMarker());
assertEquals(fqcn, other.getLoggerFqcn());
assertEquals(level, other.getLevel());
assertEquals(data, other.getMessage());
assertNull("null after serialization", other.getThrown());
assertEquals(new ThrowableProxy(t), other.getThrownProxy());
assertEquals(evt.getContextData(), other.getContextData());
assertEquals(contextStack, other.getContextStack());
assertEquals(threadName, other.getThreadName());
assertEquals(location, other.getSource());
assertEquals(12345, other.getTimeMillis());
assertEquals(678, other.getInstant().getNanoOfMillisecond());
}
@JsonProperty(JsonConstants.ELT_THROWN)
@Override
public abstract ThrowableProxy getThrownProxy();
@JsonProperty(JsonConstants.ELT_THROWN)
@Override
public abstract ThrowableProxy getThrownProxy();
@JsonProperty(JsonConstants.ELT_THROWN)
@Override
public abstract ThrowableProxy getThrownProxy();
/**
* {@inheritDoc}
*/
@Override
public void format(final LogEvent event, final StringBuilder toAppendTo) {
final ThrowableProxy proxy = event.getThrownProxy();
final Throwable throwable = event.getThrown();
//xpipe code
if(throwable != null){
if(ExceptionUtils.isSocketIoException(event.getThrown()) || ExceptionUtils.xpipeExceptionLogMessage(throwable)){
toAppendTo.append("," + throwable.getClass() + ":" + throwable.getMessage());
return;
}
String extra = ExceptionUtils.extractExtraMessage(throwable);
if(extra != null){
toAppendTo.append(String.format("\n[%s]", extra));
}
}
if ((throwable != null || proxy != null) && options.anyLines()) {
if (proxy == null) {
super.format(event, toAppendTo);
return;
}
final String extStackTrace = proxy.getExtendedStackTraceAsString(options.getPackages());
final int len = toAppendTo.length();
if (len > 0 && !Character.isWhitespace(toAppendTo.charAt(len - 1))) {
toAppendTo.append(' ');
}
if (!options.allLines() || !Constants.LINE_SEPARATOR.equals(options.getSeparator())) {
final StringBuilder sb = new StringBuilder();
final String[] array = extStackTrace.split(Constants.LINE_SEPARATOR);
final int limit = options.minLines(array.length) - 1;
for (int i = 0; i <= limit; ++i) {
sb.append(array[i]);
if (i < limit) {
sb.append(options.getSeparator());
}
}
toAppendTo.append(sb.toString());
} else {
toAppendTo.append(extStackTrace);
}
}
}
@Override
public ThrowableProxy getThrownProxy() {
return null;
}
/**
* Returns the Throwable associated with the event, if any.
* @return the Throwable.
*/
@Override
public ThrowableProxy getThrownProxy() {
return event.getThrownProxy();
}
@JsonProperty(JsonConstants.ELT_SUPPRESSED)
public abstract ThrowableProxy[] getSuppressedProxies();
@Override
public ThrowableProxy getThrownProxy() {
return event.getThrownProxy();
}
@JsonProperty(JsonConstants.ELT_THROWN)
@Override
public abstract ThrowableProxy getThrownProxy();
@JsonProperty(JsonConstants.ELT_SUPPRESSED)
public abstract ThrowableProxy[] getSuppressedProxies();
@JsonProperty(JsonConstants.ELT_SUPPRESSED)
public abstract ThrowableProxy[] getSuppressedProxies();
@JsonProperty(JsonConstants.ELT_THROWN)
@Override
public abstract ThrowableProxy getThrownProxy();
@Test
public void testToImmutable_AbstractLogEventWrapperEntity() {
final LogEvent logEvent = new AbstractLogEventWrapperEntity() {
private static final long serialVersionUID = 2L;
@Override
public ContextStack getContextStack() {
return null;
}
@Override
public Level getLevel() {
return null;
}
@Override
public String getLoggerFqcn() {
return null;
}
@Override
public String getLoggerName() {
return null;
}
@Override
public Marker getMarker() {
return null;
}
@Override
public Message getMessage() {
return null;
}
@Override
public Instant getInstant() {
return new MutableInstant();
}
@Override
public long getNanoTime() {
return 0;
}
@Override
public StackTraceElement getSource() {
return null;
}
@Override
public long getThreadId() {
return 0;
}
@Override
public String getThreadName() {
return null;
}
@Override
public int getThreadPriority() {
return 0;
}
@Override
public Throwable getThrown() {
return null;
}
@Override
public ThrowableProxy getThrownProxy() {
return null;
}
@Override
public long getTimeMillis() {
return 0;
}
};
Assert.assertNotSame(logEvent, logEvent.toImmutable());
}