Skip to content

Commit

Permalink
Renames and code reorg to prepare for release (#56)
Browse files Browse the repository at this point in the history
* Renames and code reorg to prepare for release

* Further renames after syncing on design

* Formatting
  • Loading branch information
stevejgordon authored Mar 25, 2024
1 parent 2957f54 commit 5150551
Show file tree
Hide file tree
Showing 19 changed files with 94 additions and 81 deletions.
6 changes: 3 additions & 3 deletions examples/Example.Console/Usage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,14 @@ public static async Task BasicBuilderUsageAsync()
// NOTE: This sample assumes ENV VARs have been set to configure the Endpoint and Authorization header.

// Build an agent by creating and using an agent builder, adding a single source (for traces and metrics) defined in this sample application.
await using var agent = new AgentBuilder(ActivitySourceName).Build();
await using var agent = new ElasticOpenTelemetryBuilder(ActivitySourceName).Build();

// This example adds the application activity source and fully customises the resource
await using var agent3 = new AgentBuilder(ActivitySourceName)
await using var agent3 = new ElasticOpenTelemetryBuilder(ActivitySourceName)
.WithTracing(b => b.ConfigureResource(r => r.Clear().AddService("CustomServiceName", serviceVersion: "2.2.2")))
.Build();

await using var agent4 = new AgentBuilder()
await using var agent4 = new ElasticOpenTelemetryBuilder()
.WithTracing(t => t
.ConfigureResource(rb => rb.AddService("TracerProviderBuilder", "3.3.3"))
.AddRedisInstrumentation() // This can currently only be achieved using this overload or adding Elastic processors to the TPB (as below)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public static class OpenTelemetryServicesExtensions
/// </returns>
public static global::OpenTelemetry.IOpenTelemetryBuilder AddOpenTelemetry(
this global::Microsoft.Extensions.DependencyInjection.IServiceCollection services
, AgentBuilderOptions options
, ElasticOpenTelemetryOptions options
)
{
if (options.Services == null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public static class ServiceCollectionExtensions
/// <param name="serviceCollection"></param>
/// <returns></returns>
public static IOpenTelemetryBuilder AddElasticOpenTelemetry(this IServiceCollection serviceCollection) =>
serviceCollection.AddElasticOpenTelemetry(new AgentBuilderOptions { Services = serviceCollection });
serviceCollection.AddElasticOpenTelemetry(new ElasticOpenTelemetryOptions { Services = serviceCollection });

/// <summary>
/// TODO
Expand All @@ -30,22 +30,22 @@ public static IOpenTelemetryBuilder AddElasticOpenTelemetry(this IServiceCollect
/// <param name="activitySourceNames"></param>
/// <returns></returns>
public static IOpenTelemetryBuilder AddElasticOpenTelemetry(this IServiceCollection serviceCollection, params string[]? activitySourceNames) =>
serviceCollection.AddElasticOpenTelemetry(new AgentBuilderOptions { Services = serviceCollection, ActivitySources = activitySourceNames ?? [] });
serviceCollection.AddElasticOpenTelemetry(new ElasticOpenTelemetryOptions { Services = serviceCollection, ActivitySources = activitySourceNames ?? [] });

/// <summary>
/// TODO
/// </summary>
/// <param name="serviceCollection"></param>
/// <param name="options"><see cref="AgentBuilderOptions"/></param>
/// <param name="options"><see cref="ElasticOpenTelemetryOptions"/></param>
/// <returns></returns>
public static IOpenTelemetryBuilder AddElasticOpenTelemetry(this IServiceCollection serviceCollection, AgentBuilderOptions options)
public static IOpenTelemetryBuilder AddElasticOpenTelemetry(this IServiceCollection serviceCollection, ElasticOpenTelemetryOptions options)
{
if (serviceCollection.Any(d => d.ServiceType == typeof(IHostedService) && d.ImplementationType == typeof(ElasticOtelDistroService)))
{
// TODO - Can we avoid this by storing the instance on the builder (internal access)
var sp = serviceCollection.BuildServiceProvider();
return sp.GetService<AgentBuilder>()!; //already registered as singleton
return sp.GetService<ElasticOpenTelemetryBuilder>()!; //already registered as singleton
}
return new AgentBuilder(options);
return new ElasticOpenTelemetryBuilder(options);
}
}
4 changes: 2 additions & 2 deletions src/Elastic.OpenTelemetry/Diagnostics/LoggerMessages.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ internal static partial class LoggerMessages
public static void LogAgentPreamble(this ILogger logger)
{
var process = Process.GetCurrentProcess();
logger.LogInformation("Elastic OpenTelemetry Distribution: {AgentInformationalVersion}", Agent.InformationalVersion);
if (logger is AgentCompositeLogger agentLogger)
logger.LogInformation("Elastic OpenTelemetry Distribution: {AgentInformationalVersion}", VersionHelper.InformationalVersion);
if (logger is CompositeLogger agentLogger)
{
if (agentLogger.LogFileEnabled)
logger.LogInformation("Elastic OpenTelemetry Distribution, log file: {LogFilePath}", agentLogger.LogFilePath);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
namespace Elastic.OpenTelemetry.Diagnostics.Logging;

/// <summary> A composite logger for use inside the agent, will dispose <see cref="Logging.FileLogger"/> </summary>
internal sealed class AgentCompositeLogger(ILogger? additionalLogger) : IDisposable, IAsyncDisposable, ILogger
internal sealed class CompositeLogger(ILogger? additionalLogger) : IDisposable, IAsyncDisposable, ILogger
{
public FileLogger FileLogger { get; } = new();

Expand Down
5 changes: 2 additions & 3 deletions src/Elastic.OpenTelemetry/Elastic.OpenTelemetry.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,15 @@
<PackageReference Include="OpenTelemetry.Instrumentation.EntityFrameworkCore" Version="1.0.0-beta.9" />
<PackageReference Include="OpenTelemetry.Instrumentation.Runtime" Version="1.7.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.Process" Version="0.5.0-beta.4" />
<PackageReference Include="Polyfill" Version="3.0.0" PrivateAssets="All"
IncludeAssets="runtime; build; native; contentfiles; analyzers; buildtransitive"/>
<PackageReference Include="Polyfill" Version="3.0.0" PrivateAssets="All" IncludeAssets="runtime; build; native; contentfiles; analyzers; buildtransitive" />
</ItemGroup>

<ItemGroup Condition="$(TargetFramework.StartsWith('netstandard2')) OR $(TargetFramework.StartsWith('net4'))">
<PackageReference Include="System.Threading.Channels" Version="8.0.0" />
</ItemGroup>

<ItemGroup>
<InternalsVisibleTo Include="Elastic.OpenTelemetry.Tests" Key="$(ExposedPublicKey)"/>
<InternalsVisibleTo Include="Elastic.OpenTelemetry.Tests" Key="$(ExposedPublicKey)" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -16,27 +16,27 @@
namespace Elastic.OpenTelemetry;

/// <summary>
/// Supports building <see cref="IAgent"/> instances which include Elastic defaults, but can also be customised.
/// Supports building <see cref="IInstrumentationLifetime"/> instances which include Elastic defaults, but can also be customised.
/// </summary>
public class AgentBuilder : IOpenTelemetryBuilder
public class ElasticOpenTelemetryBuilder : IOpenTelemetryBuilder
{
internal AgentCompositeLogger Logger { get; }
internal CompositeLogger Logger { get; }
internal LoggingEventListener EventListener { get; }

/// <inheritdoc cref="IOpenTelemetryBuilder.Services"/>
public IServiceCollection Services { get; }

/// <summary> TODO </summary>
public AgentBuilder(params string[] activitySourceNames) : this(new AgentBuilderOptions
public ElasticOpenTelemetryBuilder(params string[] activitySourceNames) : this(new ElasticOpenTelemetryOptions
{
ActivitySources = activitySourceNames
})
{ }

/// <summary> TODO </summary>
public AgentBuilder(AgentBuilderOptions options)
public ElasticOpenTelemetryBuilder(ElasticOpenTelemetryOptions options)
{
Logger = new AgentCompositeLogger(options.Logger);
Logger = new CompositeLogger(options.Logger);

// Enables logging of OpenTelemetry-SDK event source events
EventListener = new LoggingEventListener(Logger);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@
namespace Elastic.OpenTelemetry;

/// <summary>
/// Expert options to provide to <see cref="AgentBuilder"/> to control its initial OpenTelemetry registration
/// Expert options to provide to <see cref="ElasticOpenTelemetryBuilder"/> to control its initial OpenTelemetry registration
/// </summary>
public record AgentBuilderOptions
public record ElasticOpenTelemetryOptions
{
/// <summary>
/// Provide an additional logger to the internal file logger.
Expand All @@ -34,7 +34,7 @@ public record AgentBuilderOptions
public string[] ActivitySources { get; init; } = [];

/// <summary>
/// Stops <see cref="AgentBuilder"/> to register OLTP exporters, useful for testing scenarios
/// Stops <see cref="ElasticOpenTelemetryBuilder"/> to register OLTP exporters, useful for testing scenarios
/// </summary>
public bool SkipOtlpExporter { get; init; }

Expand Down
12 changes: 12 additions & 0 deletions src/Elastic.OpenTelemetry/EmptyInstrumentationLifetime.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information

namespace Elastic.OpenTelemetry;

internal class EmptyInstrumentationLifetime : IInstrumentationLifetime
{
public void Dispose() { }

public ValueTask DisposeAsync() => default;
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,33 +10,32 @@
using OpenTelemetry.Metrics;
using OpenTelemetry.Trace;

namespace Elastic.OpenTelemetry;
namespace Elastic.OpenTelemetry.Extensions;

/// <summary> TODO </summary>
public static class OpenTelemetryBuilderExtensions
{
/// <summary> TODO </summary>
public static IOpenTelemetryBuilder WithLogger(this IOpenTelemetryBuilder builder, ILogger logger)
{
if (builder is not AgentBuilder agentBuilder)
if (builder is not ElasticOpenTelemetryBuilder agentBuilder)
return builder;

agentBuilder.Logger.SetAdditionalLogger(logger);
return agentBuilder;
}


/// <summary>
/// Build an instance of <see cref="IAgent"/>.
/// Build an instance of <see cref="IInstrumentationLifetime"/>.
/// </summary>
/// <returns>A new instance of <see cref="IAgent"/>.</returns>
public static IAgent Build(this IOpenTelemetryBuilder builder, ILogger? logger = null, IServiceProvider? serviceProvider = null)
/// <returns>A new instance of <see cref="IInstrumentationLifetime"/>.</returns>
public static IInstrumentationLifetime Build(this IOpenTelemetryBuilder builder, ILogger? logger = null, IServiceProvider? serviceProvider = null)
{
// this happens if someone calls Build() while using IServiceCollection and AddOpenTelemetry() and NOT Add*Elastic*OpenTelemetry()
// we treat this a NOOP
// NOTE for AddElasticOpenTelemetry(this IServiceCollection services) calling Build() manually is NOT required.
if (builder is not AgentBuilder agentBuilder)
return new EmptyAgent();
if (builder is not ElasticOpenTelemetryBuilder agentBuilder)
return new EmptyInstrumentationLifetime();

var log = agentBuilder.Logger;

Expand All @@ -46,40 +45,9 @@ public static IAgent Build(this IOpenTelemetryBuilder builder, ILogger? logger =
var tracerProvider = sp.GetService<TracerProvider>()!;
var meterProvider = sp.GetService<MeterProvider>()!;

var agent = new ElasticAgent(log, agentBuilder.EventListener, tracerProvider, meterProvider);
var agent = new InstrumentationLifetime(log, agentBuilder.EventListener, tracerProvider, meterProvider);
log.LogAgentBuilderBuiltAgent();
return agent;
}
}

internal class EmptyAgent : IAgent
{
public void Dispose() { }

public ValueTask DisposeAsync() => default;
}

internal class ElasticAgent(
AgentCompositeLogger logger,
LoggingEventListener loggingEventListener,
TracerProvider tracerProvider,
MeterProvider meterProvider
) : IAgent
{
public void Dispose()
{
tracerProvider.Dispose();
meterProvider.Dispose();
loggingEventListener.Dispose();
logger.Dispose();
}

public async ValueTask DisposeAsync()
{
tracerProvider.Dispose();
meterProvider.Dispose();
await loggingEventListener.DisposeAsync().ConfigureAwait(false);
await logger.DisposeAsync().ConfigureAwait(false);
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,6 @@ internal static ResourceBuilder AddDistroAttributes(this ResourceBuilder builder
builder.AddAttributes(new Dictionary<string, object>
{
{ ResourceSemanticConventions.AttributeTelemetryDistroName, "elastic-dotnet" },
{ ResourceSemanticConventions.AttributeTelemetryDistroVersion, Agent.InformationalVersion }
{ ResourceSemanticConventions.AttributeTelemetryDistroVersion, VersionHelper.InformationalVersion }
});
}
5 changes: 3 additions & 2 deletions src/Elastic.OpenTelemetry/Hosting/ElasticOtelDistroService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information

using Elastic.OpenTelemetry.Extensions;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
Expand All @@ -10,14 +11,14 @@ namespace Elastic.OpenTelemetry.Hosting;

internal sealed class ElasticOtelDistroService(IServiceProvider serviceProvider) : IHostedLifecycleService
{
private IAgent? _agent;
private IInstrumentationLifetime? _agent;

public Task StartingAsync(CancellationToken cancellationToken)
{
var loggerFactory = serviceProvider.GetService<ILoggerFactory>();
var logger = loggerFactory?.CreateLogger($"{nameof(Elastic)}.{nameof(OpenTelemetry)}");

_agent = serviceProvider.GetRequiredService<AgentBuilder>().Build(logger, serviceProvider);
_agent = serviceProvider.GetRequiredService<ElasticOpenTelemetryBuilder>().Build(logger, serviceProvider);

//logger.LogInformation("Initialising Agent.Current.");
//Agent.SetAgent(_agent, logger);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@
namespace Elastic.OpenTelemetry;

/// <summary>
/// An Elastic OpenTelemetry Distribution agent.
/// A logical Elastic OpenTelemetry Distribution.
/// </summary>
public interface IAgent : IDisposable, IAsyncDisposable;
public interface IInstrumentationLifetime : IDisposable, IAsyncDisposable;
34 changes: 34 additions & 0 deletions src/Elastic.OpenTelemetry/InstrumentationLifetime.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information

using Elastic.OpenTelemetry.Diagnostics;
using Elastic.OpenTelemetry.Diagnostics.Logging;
using OpenTelemetry.Metrics;
using OpenTelemetry.Trace;

namespace Elastic.OpenTelemetry;

internal class InstrumentationLifetime(
CompositeLogger logger,
LoggingEventListener loggingEventListener,
TracerProvider tracerProvider,
MeterProvider meterProvider
) : IInstrumentationLifetime
{
public void Dispose()
{
tracerProvider.Dispose();
meterProvider.Dispose();
loggingEventListener.Dispose();
logger.Dispose();
}

public async ValueTask DisposeAsync()
{
tracerProvider.Dispose();
meterProvider.Dispose();
await loggingEventListener.DisposeAsync().ConfigureAwait(false);
await logger.DisposeAsync().ConfigureAwait(false);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,11 @@

namespace Elastic.OpenTelemetry;

/// <summary>
/// Supports building and accessing an <see cref="IAgent"/> which collects and ships observability signals.
/// </summary>
public static class Agent
internal static class VersionHelper
{
static Agent()
static VersionHelper()
{
var assemblyInformationalVersion = typeof(Agent).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;
var assemblyInformationalVersion = typeof(VersionHelper).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;
InformationalVersion = ParseAssemblyInformationalVersion(assemblyInformationalVersion);
}

Expand Down
5 changes: 3 additions & 2 deletions tests/Elastic.OpenTelemetry.Tests/LoggingTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information

using Elastic.OpenTelemetry.Extensions;
using OpenTelemetry;
using Xunit.Abstractions;

Expand All @@ -13,12 +14,12 @@ public class LoggingTests(ITestOutputHelper output)
public async Task ObserveLogging()
{
var logger = new TestLogger(output);
var options = new AgentBuilderOptions { Logger = logger, SkipOtlpExporter = true };
var options = new ElasticOpenTelemetryOptions { Logger = logger, SkipOtlpExporter = true };
const string activitySourceName = nameof(ObserveLogging);

var activitySource = new ActivitySource(activitySourceName, "1.0.0");

await using (new AgentBuilder(options)
await using (new ElasticOpenTelemetryBuilder(options)
.WithTracing(tpb => tpb
.ConfigureResource(rb => rb.AddService("Test", "1.0.0"))
.AddSource(activitySourceName)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public class ServiceCollectionTests(ITestOutputHelper output)
[Fact]
public async Task ServiceCollectionAddIsSafeToCallMultipleTimes()
{
var options = new AgentBuilderOptions { Logger = new TestLogger(output), SkipOtlpExporter = true };
var options = new ElasticOpenTelemetryOptions { Logger = new TestLogger(output), SkipOtlpExporter = true };

const string activitySourceName = nameof(ServiceCollectionAddIsSafeToCallMultipleTimes);
var activitySource = new ActivitySource(activitySourceName, "1.0.0");
Expand Down
Loading

0 comments on commit 5150551

Please sign in to comment.