Skip to content
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

Add ReadWriteLogRecord#getContext #4888

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
package io.opentelemetry.sdk.logs;

import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.context.Context;
import io.opentelemetry.sdk.logs.data.LogRecordData;

/** A log record that can be read from and written to. */
Expand All @@ -24,6 +25,9 @@ public interface ReadWriteLogRecord {
/** Return an immutable {@link LogRecordData} instance representing this log record. */
LogRecordData toLogRecordData();

/** Return the log record {@link Context}. */
Context getContext();

// TODO: add additional log record accessors. Currently, all fields can be accessed indirectly via
// #toLogRecordData() with at the expense of additional allocations.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@
import io.opentelemetry.api.logs.EventBuilder;
import io.opentelemetry.api.logs.LogRecordBuilder;
import io.opentelemetry.api.logs.Severity;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.SpanContext;
import io.opentelemetry.context.Context;
import io.opentelemetry.sdk.common.InstrumentationScopeInfo;
import io.opentelemetry.sdk.internal.AttributesMap;
Expand All @@ -27,7 +25,7 @@ final class SdkLogRecordBuilder implements EventBuilder {

private final InstrumentationScopeInfo instrumentationScopeInfo;
private long epochNanos;
private SpanContext spanContext = SpanContext.getInvalid();
@Nullable private Context context;
private Severity severity = Severity.UNDEFINED_SEVERITY_NUMBER;
@Nullable private String severityText;
private Body body = Body.empty();
Expand All @@ -54,7 +52,7 @@ public SdkLogRecordBuilder setEpoch(Instant instant) {

@Override
public SdkLogRecordBuilder setContext(Context context) {
this.spanContext = Span.fromContext(context).getSpanContext();
this.context = context;
return this;
}

Expand Down Expand Up @@ -103,7 +101,7 @@ public void emit() {
loggerSharedState.getResource(),
instrumentationScopeInfo,
this.epochNanos == 0 ? this.loggerSharedState.getClock().now() : this.epochNanos,
spanContext,
this.context == null ? Context.current() : this.context,
severity,
severityText,
body,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.internal.GuardedBy;
import io.opentelemetry.api.logs.Severity;
import io.opentelemetry.api.trace.SpanContext;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.context.Context;
import io.opentelemetry.sdk.common.InstrumentationScopeInfo;
import io.opentelemetry.sdk.internal.AttributesMap;
import io.opentelemetry.sdk.logs.data.Body;
Expand All @@ -25,7 +26,7 @@ class SdkReadWriteLogRecord implements ReadWriteLogRecord {
private final Resource resource;
private final InstrumentationScopeInfo instrumentationScopeInfo;
private final long epochNanos;
private final SpanContext spanContext;
private final Context context;
Copy link
Member

Choose a reason for hiding this comment

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

I think(?) the reason that SdkSpan only contains SpanContext instead of the full Context was to limit memory retention, @jkwatson do you recall anything?

Copy link
Member Author

Choose a reason for hiding this comment

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

Ok so there is a subtle difference between holding it in the SdkReadWriteLogRecord and holding it in the SdkLogRecordBuilder such that it can be passed to each log processor as an argument LogRecordProcessor#onEmit.

If its held in SdkReadWriteLogRecord, there's a reference to Context until BatchLogRecordProcessor flushes and converts each log record to LogRecordData, so the reference sticks around for essentially the shorter of the batch interval or the time it takes to fill the batch queue.

If instead the context is held in SdkLogRecordBuilder and passed as an argument to each LogRecordProcessor#onEmit(), then the reference only has to stick around until the last processor has synchronously returns from onEmit. This allows the context to be garbage collected while the corresponding log record is still sitting in the BatchLogRecordProcessor queue.

I think this is a good enough reason to include as an argument to onEmit() instead of having a getter on SdkReadWriteLogRecord.

private final Severity severity;
@Nullable private final String severityText;
private final Body body;
Expand All @@ -40,7 +41,7 @@ private SdkReadWriteLogRecord(
Resource resource,
InstrumentationScopeInfo instrumentationScopeInfo,
long epochNanos,
SpanContext spanContext,
Context context,
Severity severity,
@Nullable String severityText,
Body body,
Expand All @@ -49,7 +50,7 @@ private SdkReadWriteLogRecord(
this.resource = resource;
this.instrumentationScopeInfo = instrumentationScopeInfo;
this.epochNanos = epochNanos;
this.spanContext = spanContext;
this.context = context;
this.severity = severity;
this.severityText = severityText;
this.body = body;
Expand All @@ -62,7 +63,7 @@ static SdkReadWriteLogRecord create(
Resource resource,
InstrumentationScopeInfo instrumentationScopeInfo,
long epochNanos,
SpanContext spanContext,
Context context,
Severity severity,
@Nullable String severityText,
Body body,
Expand All @@ -72,7 +73,7 @@ static SdkReadWriteLogRecord create(
resource,
instrumentationScopeInfo,
epochNanos,
spanContext,
context,
severity,
severityText,
body,
Expand Down Expand Up @@ -111,12 +112,17 @@ public LogRecordData toLogRecordData() {
resource,
instrumentationScopeInfo,
epochNanos,
spanContext,
Span.fromContext(context).getSpanContext(),
severity,
severityText,
body,
getImmutableAttributes(),
attributes == null ? 0 : attributes.getTotalAddedValues());
}
}

@Override
public Context getContext() {
return context;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

import static io.opentelemetry.sdk.testing.assertj.LogAssertions.assertThat;
import static org.assertj.core.api.Assertions.as;
import static org.assertj.core.api.Assertions.entry;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
Expand All @@ -21,6 +22,8 @@
import io.opentelemetry.api.trace.TraceFlags;
import io.opentelemetry.api.trace.TraceState;
import io.opentelemetry.context.Context;
import io.opentelemetry.context.ContextKey;
import io.opentelemetry.context.Scope;
import io.opentelemetry.internal.testing.slf4j.SuppressLogger;
import io.opentelemetry.sdk.common.Clock;
import io.opentelemetry.sdk.common.CompletableResultCode;
Expand All @@ -29,6 +32,7 @@
import io.opentelemetry.sdk.resources.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import org.assertj.core.api.InstanceOfAssertFactories;
Expand Down Expand Up @@ -262,6 +266,49 @@ void loggerBuilder_WithLogRecordProcessor() {
Attributes.builder().put("k1", "new-v1").put("k2", "v2").put("k3", "v3").build());
}

@Test
void loggerBuilder_ProcessorWithContext() {
ContextKey<String> contextKey = ContextKey.named("my-context-key");
AtomicReference<LogRecordData> logRecordData = new AtomicReference<>();

sdkLoggerProvider =
SdkLoggerProvider.builder()
.addLogRecordProcessor(
logRecord ->
logRecord.setAttribute(
AttributeKey.stringKey("my-context-key"),
Optional.ofNullable(logRecord.getContext().get(contextKey)).orElse("")))
.addLogRecordProcessor(logRecord -> logRecordData.set(logRecord.toLogRecordData()))
.build();

// With implicit context
try (Scope unused = Context.current().with(contextKey, "context-value1").makeCurrent()) {
sdkLoggerProvider
.loggerBuilder("test")
.build()
.logRecordBuilder()
.setBody("log message1")
.emit();
}
assertThat(logRecordData.get())
.hasBody("log message1")
.hasAttributes(entry(AttributeKey.stringKey("my-context-key"), "context-value1"));

// With explicit context
try (Scope unused = Context.current().with(contextKey, "context-value2").makeCurrent()) {
sdkLoggerProvider
.loggerBuilder("test")
.build()
.logRecordBuilder()
.setContext(Context.current())
.setBody("log message2")
.emit();
}
assertThat(logRecordData.get())
.hasBody("log message2")
.hasAttributes(entry(AttributeKey.stringKey("my-context-key"), "context-value2"));
}

@Test
void forceFlush() {
sdkLoggerProvider.forceFlush();
Expand Down