in src/Elastic.OpenTelemetry.Core/SignalBuilder.cs [102:159]
public static T WithElasticDefaults<T>(
T builder,
CompositeElasticOpenTelemetryOptions? options,
ElasticOpenTelemetryComponents? components,
IServiceCollection? services,
Action<T, BuilderState, IServiceCollection?> configure) where T : class
{
var providerBuilderName = builder.GetType().Name;
var logger = GetLogger(components, options);
try
{
if (BuilderStateTable.TryGetValue(builder, out var builderState))
{
builderState.Components.Logger.LogBuilderAlreadyConfigured(providerBuilderName, builderState.InstanceIdentifier);
// This allows us to track the number of times a specific instance of a builder is configured.
// We expect each builder to be configured at most once and log a warning if multiple invocations
// are detected.
builderState.IncrementWithElasticDefaults();
if (builderState.WithElasticDefaultsCounter > 1)
builderState.Components.Logger.LogWarning("The `WithElasticDefaults` method has been called {WithElasticDefaultsCount} " +
"times on the same `{BuilderType}` (instance: {BuilderInstanceId}). This method is " +
"expected to be invoked a maximum of one time.", builderState.WithElasticDefaultsCounter, providerBuilderName,
builderState.InstanceIdentifier);
return builder;
}
// This should not be a hot path, so locking here is reasonable.
using (var scope = Lock.EnterScope())
{
var instanceId = Guid.NewGuid().ToString(); // Used in logging to track duplicate calls to the same builder
// We can't log to the file here as we don't yet have any bootstrapped components.
// Therefore, this message will only appear if the consumer provides an additional logger.
// This is fine as it's a trace level message for advanced debugging.
logger.LogNoExistingComponents(providerBuilderName, instanceId);
options ??= CompositeElasticOpenTelemetryOptions.DefaultOptions;
components = ElasticOpenTelemetry.Bootstrap(options, services);
builderState = new BuilderState(components, instanceId);
configure(builder, builderState, services);
components.Logger.LogStoringBuilderState(providerBuilderName, instanceId);
BuilderStateTable.Add(builder, builderState);
}
}
catch (Exception ex)
{
logger.LogError(new EventId(502, "BuilderDefaultsFailed"), ex, "Failed to fully register EDOT .NET " +
"defaults on the {ProviderBuilderName}.", builder.GetType().Name);
}
return builder;
}