opentelemetry-java: Attach original Exception to Event in Span#recordException

I am using the SDK reference implementation Tracer with an implementation of SpanExporter that wraps Apache log4j2. I am adding exception events to the current Span via the recordException method which takes the exception and appends the details as attributes, including the full stack trace. I’d like to be able to include the exception information with stack trace in the logged span, however without being able to retrieve the original Throwable instance I am unable to rely on the configured pattern in log4j2 to manage formatting. As the project in question is built on Spring WebFlux the stack traces are quite large so having the ability to concisely format the exception and stack trace is important.

An ideal solution would be to have a way to negotiate original exception from the events appended to the SpanData, such as a new interface that extends from SpanData.Event that exposes the exception through a member:

public interface ExceptionEvent extends SpanData.Event {
    Throwable getException();
}

My SpanExporter implementation could then iterate through the span events to find an event that implements this interface to obtain the original exception and write it to the log, e.g.:

Throwable exception = null;
if (spanData.getTotalRecordedEvents() > 0) {
    for (SpanData.Event event : spanData.getEvents()) {
        if (event instanceof ExceptionEvent) {
            exception = ((ExceptionEvent) event).getException();
            break;
        }
    }
}

if (exception != null) {
    logger.info(spanId.toLowerBase16());
} else {
    logger.error(spanId.toLowerBase16(), exception);
}

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Comments: 15 (15 by maintainers)

Most upvoted comments

I opened https://github.com/open-telemetry/opentelemetry-specification/issues/955. It’s a bit open ended but I hope I conveyed enough information about my use case.