Skip to content

Commit

Permalink
feat: add extended exception context to EXN_STACKTRACE
Browse files Browse the repository at this point in the history
Adds the cause exception stacktrace (if exists) of the logged exception
to the `EXN_STACKTRACE` along with the original exceptions stacktrace.
  • Loading branch information
dogukancagatay committed Nov 1, 2024
1 parent 2ed5ab4 commit 6c123ed
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/main/java/com/dgkncgty/logback/SystemdJournalAppender.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.IThrowableProxy;
import ch.qos.logback.classic.spi.StackTraceElementProxy;
import ch.qos.logback.core.AppenderBase;
import ch.qos.logback.core.encoder.Encoder;
Expand All @@ -25,6 +26,7 @@
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
* An appender that send the events to systemd journal
Expand Down Expand Up @@ -96,11 +98,29 @@ protected void append(ILoggingEvent event) {
// if one wants to log the exception stack trace, just do it
if (logStackTrace) {
messages.add("EXN_STACKTRACE=%s");

// The main exception
StringWriter stacktrace = new StringWriter();
for (StackTraceElementProxy st : stack) {
stacktrace.write(st.getSTEAsString());
stacktrace.write('\n');
}

// Go down the caused by chain
IThrowableProxy cause = event.getThrowableProxy().getCause();
while (cause != null) {
stacktrace.write("Caused by: ");
stacktrace.write(cause.getClassName());
stacktrace.write(": ");
stacktrace.write(Objects.toString(cause.getMessage(), ""));
stacktrace.write("\n");
for (StackTraceElementProxy st : cause.getStackTraceElementProxyArray()) {
stacktrace.write(st.getSTEAsString());
stacktrace.write('\n');
}
cause = cause.getCause();
}

messages.add(stacktrace.toString());
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,5 +71,13 @@ public void testLogWithSourceAndException() throws Exception {
logWithSource.error("some exception", exception);
}

@Test
public void testLogWithSourceAndNestedException() {
Exception exception = new RuntimeException("some exception");
Exception exception1 = new Exception("nested exception 1", exception);
Exception exception2 = new Exception("nested exception 2", exception1);
Exception exception3 = new Exception("nested exception 3", exception2);
logWithSource.error("an exception occurred ", exception3);
}

}

0 comments on commit 6c123ed

Please sign in to comment.