Skip to content

Add custom stacktrace renderer which is length limit aware #7281

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions sdk/common/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ plugins {
id("otel.java-conventions")
id("otel.publish-conventions")
id("otel.animalsniffer-conventions")
id("otel.jmh-conventions")
}
apply<OtelVersionClassPlugin>()

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/

package io.opentelemetry.sdk.internal;

import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.concurrent.TimeUnit;
import java.util.function.BiFunction;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Threads;
import org.openjdk.jmh.annotations.Warmup;

/**
* This benchmark compares the performance of {@link StackTraceRenderer}, the custom length limit
* aware exception render, to the built-in JDK stacktrace renderer {@link
* Throwable#printStackTrace(PrintStream)}.
*/
@BenchmarkMode({Mode.AverageTime})
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 100, timeUnit = TimeUnit.MILLISECONDS)
@Measurement(iterations = 5, time = 100, timeUnit = TimeUnit.MILLISECONDS)
@Fork(1)
@SuppressWarnings("StaticAssignmentOfThrowable")
public class StacktraceRenderBenchmark {

private static final Exception simple = new Exception("error");
private static final Exception complex =
new Exception("error", new Exception("cause1", new Exception("cause2")));

static {
complex.addSuppressed(new Exception("suppressed1"));
complex.addSuppressed(new Exception("suppressed2", new Exception("cause")));
}

@State(Scope.Benchmark)
public static class BenchmarkState {

@Param Renderer renderer;
@Param ExceptionParam exceptionParam;

@Param({"10", "1000", "100000"})
int lengthLimit;
}

@SuppressWarnings("ImmutableEnumChecker")
public enum Renderer {
JDK(
(throwable, limit) -> {
StringWriter stringWriter = new StringWriter();
try (PrintWriter printWriter = new PrintWriter(stringWriter)) {
throwable.printStackTrace(printWriter);
}
String stacktrace = stringWriter.toString();
return stacktrace.substring(0, Math.min(stacktrace.length(), limit));
}),
CUSTOM((throwable, limit) -> new StackTraceRenderer(throwable, limit).render());

private final BiFunction<Throwable, Integer, String> renderer;

Renderer(BiFunction<Throwable, Integer, String> renderer) {
this.renderer = renderer;
}

BiFunction<Throwable, Integer, String> renderer() {
return renderer;
}
}

@SuppressWarnings("ImmutableEnumChecker")
public enum ExceptionParam {
SIMPLE(simple),
COMPLEX(complex);

private final Throwable throwable;

ExceptionParam(Throwable throwable) {
this.throwable = throwable;
}

Throwable throwable() {
return throwable;
}
}

@Benchmark
@Threads(1)
@SuppressWarnings("ReturnValueIgnored")
public void render(BenchmarkState benchmarkState) {
BiFunction<Throwable, Integer, String> renderer = benchmarkState.renderer.renderer();
Throwable throwable = benchmarkState.exceptionParam.throwable();
int limit = benchmarkState.lengthLimit;

renderer.apply(throwable, limit);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.common.AttributesBuilder;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
Expand Down Expand Up @@ -107,7 +105,9 @@ public static Object applyAttributeLengthLimit(Object value, int lengthLimit) {
}

public static void addExceptionAttributes(
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One thing I've considered is retaining some sort of system property / env var to fallback to the built-in JDK exception rendering. Would offer a nice escape hatch to revert to the built-in jdk rendering in case there's any bugs in the code, but downside is it would be hard to know when it would be safe to finally remove.

Throwable exception, BiConsumer<AttributeKey<String>, String> attributeConsumer) {
Throwable exception,
BiConsumer<AttributeKey<String>, String> attributeConsumer,
int lengthLimit) {
String exceptionType = exception.getClass().getCanonicalName();
if (exceptionType != null) {
attributeConsumer.accept(EXCEPTION_TYPE, exceptionType);
Expand All @@ -118,11 +118,7 @@ public static void addExceptionAttributes(
attributeConsumer.accept(EXCEPTION_MESSAGE, exceptionMessage);
}

StringWriter stringWriter = new StringWriter();
try (PrintWriter printWriter = new PrintWriter(stringWriter)) {
exception.printStackTrace(printWriter);
}
String stackTrace = stringWriter.toString();
String stackTrace = new StackTraceRenderer(exception, lengthLimit).render();
if (stackTrace != null) {
attributeConsumer.accept(EXCEPTION_STACKTRACE, stackTrace);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/

package io.opentelemetry.sdk.internal;

import java.io.PrintStream;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.Set;

/**
* An alternative to exception stacktrace renderer that replicates the behavior of {@link
* Throwable#printStackTrace(PrintStream)}, but which is aware of a maximum stacktrace length limit,
* and exits early when the length limit has been exceeded to avoid unnecessary computation.
*
* <p>Instances should only be used once.
*/
class StackTraceRenderer {

private static final String CAUSED_BY = "Caused by: ";
private static final String SUPPRESSED = "Suppressed: ";

private final Throwable throwable;
private final int lengthLimit;
private final StringBuilder builder = new StringBuilder();

StackTraceRenderer(Throwable throwable, int lengthLimit) {
this.throwable = throwable;
this.lengthLimit = lengthLimit;
}

String render() {
if (builder.length() == 0) {
appendStackTrace();
}

return builder.substring(0, Math.min(builder.length(), lengthLimit));
}

private void appendStackTrace() {
builder.append(throwable).append(System.lineSeparator());
if (isOverLimit()) {
return;
}

StackTraceElement[] stackTraceElements = throwable.getStackTrace();
for (StackTraceElement stackTraceElement : stackTraceElements) {
builder.append("\tat ").append(stackTraceElement).append(System.lineSeparator());
if (isOverLimit()) {
return;
}
}

Set<Throwable> seen = Collections.newSetFromMap(new IdentityHashMap<>());
seen.add(throwable);

for (Throwable suppressed : throwable.getSuppressed()) {
appendInnerStacktrace(stackTraceElements, suppressed, "\t", SUPPRESSED, seen);
}

Throwable cause = throwable.getCause();
if (cause != null) {
appendInnerStacktrace(stackTraceElements, cause, "", CAUSED_BY, seen);
}
}

/**
* Append the {@code innerThrowable} to the {@link #builder}, returning {@code true} if the
* builder now exceeds the length limit.
*/
private boolean appendInnerStacktrace(
StackTraceElement[] parentElements,
Throwable innerThrowable,
String prefix,
String caption,
Set<Throwable> seen) {
if (seen.contains(innerThrowable)) {
builder
.append(prefix)
.append(caption)
.append("[CIRCULAR REFERENCE: ")
.append(innerThrowable)
.append("]")
.append(System.lineSeparator());
return true;
}
seen.add(innerThrowable);

// Iterating back to front, compute the lastSharedFrameIndex, which tracks the point at which
// this exception's stacktrace elements start repeating the parent's elements
StackTraceElement[] currentElements = innerThrowable.getStackTrace();
int parentIndex = parentElements.length - 1;
int lastSharedFrameIndex = currentElements.length - 1;
while (true) {
if (parentIndex < 0 || lastSharedFrameIndex < 0) {
break;

Check warning on line 98 in sdk/common/src/main/java/io/opentelemetry/sdk/internal/StackTraceRenderer.java

View check run for this annotation

Codecov / codecov/patch

sdk/common/src/main/java/io/opentelemetry/sdk/internal/StackTraceRenderer.java#L98

Added line #L98 was not covered by tests
}
if (!parentElements[parentIndex].equals(currentElements[lastSharedFrameIndex])) {
break;
}
parentIndex--;
lastSharedFrameIndex--;
}

builder.append(prefix).append(caption).append(innerThrowable).append(System.lineSeparator());
if (isOverLimit()) {
return true;

Check warning on line 109 in sdk/common/src/main/java/io/opentelemetry/sdk/internal/StackTraceRenderer.java

View check run for this annotation

Codecov / codecov/patch

sdk/common/src/main/java/io/opentelemetry/sdk/internal/StackTraceRenderer.java#L109

Added line #L109 was not covered by tests
}

for (int i = 0; i <= lastSharedFrameIndex; i++) {
StackTraceElement stackTraceElement = currentElements[i];
builder
.append(prefix)
.append("\tat ")
.append(stackTraceElement)
.append(System.lineSeparator());
if (isOverLimit()) {
return true;

Check warning on line 120 in sdk/common/src/main/java/io/opentelemetry/sdk/internal/StackTraceRenderer.java

View check run for this annotation

Codecov / codecov/patch

sdk/common/src/main/java/io/opentelemetry/sdk/internal/StackTraceRenderer.java#L120

Added line #L120 was not covered by tests
}
}

int duplicateFrames = currentElements.length - 1 - lastSharedFrameIndex;
if (duplicateFrames != 0) {
builder
.append(prefix)
.append("\t... ")
.append(duplicateFrames)
.append(" more")
.append(System.lineSeparator());
if (isOverLimit()) {
return true;

Check warning on line 133 in sdk/common/src/main/java/io/opentelemetry/sdk/internal/StackTraceRenderer.java

View check run for this annotation

Codecov / codecov/patch

sdk/common/src/main/java/io/opentelemetry/sdk/internal/StackTraceRenderer.java#L133

Added line #L133 was not covered by tests
}
}

for (Throwable suppressed : innerThrowable.getSuppressed()) {
if (appendInnerStacktrace(currentElements, suppressed, prefix + "\t", SUPPRESSED, seen)) {
return true;
}
}

Throwable cause = innerThrowable.getCause();
if (cause != null) {
return appendInnerStacktrace(currentElements, cause, prefix, CAUSED_BY, seen);
}

return false;
}

private boolean isOverLimit() {
return builder.length() >= lengthLimit;
}
}
Loading
Loading