Skip to content
Merged
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)) {
Comment thread
jack-berg marked this conversation as resolved.
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 @@ -9,19 +9,24 @@
import java.io.StringWriter;

/**
* This class is internal and experimental. Its APIs are unstable and can change at any time. Its
* The default {@link ExceptionAttributeResolver}, populating standard {@code exception.*} as
* defined by the semantic conventions.
*
* <p>This class is internal and experimental. Its APIs are unstable and can change at any time. Its
* APIs (or a version of them) may be promoted to the public stable API in the future, but no
* guarantees are made.
*
* @see ExceptionAttributeResolver#getDefault()
* @see ExceptionAttributeResolver#getDefault(boolean) ()
*/
public final class DefaultExceptionAttributeResolver implements ExceptionAttributeResolver {
final class DefaultExceptionAttributeResolver implements ExceptionAttributeResolver {

private static final DefaultExceptionAttributeResolver INSTANCE =
new DefaultExceptionAttributeResolver();
static final String ENABLE_JVM_STACKTRACE_PROPERTY = "otel.experimental.sdk.jvm_stacktrace";

private DefaultExceptionAttributeResolver() {}
private final boolean jvmStacktraceEnabled;

public static ExceptionAttributeResolver getInstance() {
return INSTANCE;
DefaultExceptionAttributeResolver(boolean jvmStacktraceEnabled) {
this.jvmStacktraceEnabled = jvmStacktraceEnabled;
}

@Override
Expand All @@ -37,14 +42,23 @@ public void setExceptionAttributes(
attributeSetter.setAttribute(ExceptionAttributeResolver.EXCEPTION_MESSAGE, exceptionMessage);
}

String exceptionStacktrace =
jvmStacktraceEnabled
? jvmStacktrace(throwable)
: limitsAwareStacktrace(throwable, maxAttributeLength);
attributeSetter.setAttribute(
ExceptionAttributeResolver.EXCEPTION_STACKTRACE, exceptionStacktrace);
}

private static String jvmStacktrace(Throwable throwable) {
StringWriter stringWriter = new StringWriter();
try (PrintWriter printWriter = new PrintWriter(stringWriter)) {
throwable.printStackTrace(printWriter);
}
String exceptionStacktrace = stringWriter.toString();
if (exceptionStacktrace != null) {
attributeSetter.setAttribute(
ExceptionAttributeResolver.EXCEPTION_STACKTRACE, exceptionStacktrace);
}
return stringWriter.toString();
}

private static String limitsAwareStacktrace(Throwable throwable, int maxAttributeLength) {
return new StackTraceRenderer(throwable, maxAttributeLength).render();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@

package io.opentelemetry.sdk.internal;

import static io.opentelemetry.sdk.internal.DefaultExceptionAttributeResolver.ENABLE_JVM_STACKTRACE_PROPERTY;

import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.internal.ConfigUtil;
import javax.annotation.Nullable;

/**
Expand All @@ -24,6 +27,26 @@ public interface ExceptionAttributeResolver {
void setExceptionAttributes(
AttributeSetter attributeSetter, Throwable throwable, int maxAttributeLength);

/**
* Return the default exception attribute resolver, setting {@code jvmStacktraceEnabled} based on
* {@link DefaultExceptionAttributeResolver#ENABLE_JVM_STACKTRACE_PROPERTY}.
*/
static ExceptionAttributeResolver getDefault() {
return getDefault(
Boolean.parseBoolean(ConfigUtil.getString(ENABLE_JVM_STACKTRACE_PROPERTY, "false")));
}

/**
* Return the default exception attribute resolver.
*
* @param jvmStacktraceEnabled if true, resolve stacktrace using the stacktrace renderer built
* into the JVM. This built in JVM renderer is not attribute limits aware, and may utilize
* more CPU / memory than is needed. Most users will prefer to set this to {@code false}.
*/
static ExceptionAttributeResolver getDefault(boolean jvmStacktraceEnabled) {
return new DefaultExceptionAttributeResolver(jvmStacktraceEnabled);
}

/**
* This class is internal and experimental. Its APIs are unstable and can change at any time. Its
* APIs (or a version of them) may be promoted to the public stable API in the future, but no
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