Skip to content

Commit

Permalink
HostBuilderExtensions.UseElasticApm: subscribe to subscribers params (
Browse files Browse the repository at this point in the history
#1060)

* HostBuilderExtensions.UseElasticApm: subscribe to `subscribers` parameter

Fixes #1059

* Update HostBuilderExtensionTests.cs

Add test to cover `enabled=false` case.

* Update HostBuilderExtensions.cs

Resolve AgentComponents only once.

* Update HostBuilderExtensions.cs
  • Loading branch information
gregkalapos authored Nov 24, 2020
1 parent 4f4a543 commit 997d924
Show file tree
Hide file tree
Showing 3 changed files with 93 additions and 17 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,25 @@

<PropertyGroup>
<PackageId>Elastic.Apm.Extensions.Hosting</PackageId>
<Description>Elastic APM .NET Agent. This package offers integration with Microsoft.Extensions.Hosting.IHostBuilder for agent registration </Description>
<Description>Elastic APM .NET Agent. This package offers integration with Microsoft.Extensions.Hosting.IHostBuilder for agent registration</Description>
<PackageTags>apm, monitoring, elastic, elasticapm, analytics, netcore</PackageTags>
<TargetFrameworks>netstandard2.0;netcoreapp3.0</TargetFrameworks>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\Elastic.Apm\Elastic.Apm.csproj" />
<ProjectReference Include="..\Elastic.Apm\Elastic.Apm.csproj"/>
</ItemGroup>

<ItemGroup Condition=" '$(TargetFramework)' == 'netstandard2.0' ">
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="2.1.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="2.1.0" />
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="2.1.0"/>
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="2.1.0"/>
<PackageReference Include="Microsoft.Extensions.DependencyInjection " Version="2.1.0"/>
</ItemGroup>

<ItemGroup Condition=" '$(TargetFramework)' == 'netcoreapp3.0' ">
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="3.0.0"/>
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="3.0.0"/>
<PackageReference Include="Microsoft.Extensions.DependencyInjection " Version="3.0.0"/>
</ItemGroup>

</Project>
20 changes: 12 additions & 8 deletions src/Elastic.Apm.Extensions.Hosting/HostBuilderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,11 @@ public static IHostBuilder UseElasticApm(this IHostBuilder builder, params IDiag
builder.ConfigureServices((ctx, services) =>
{
//If the static agent doesn't exist, we create one here. If there is already 1 agent created, we reuse it.

if (!Agent.IsConfigured)
{
services.AddSingleton<IApmLogger, NetCoreLogger>();
services.AddSingleton<IConfigurationReader>(sp =>
new MicrosoftExtensionsConfig(ctx.Configuration, sp.GetService<IApmLogger>(), ctx.HostingEnvironment.EnvironmentName));
new MicrosoftExtensionsConfig(ctx.Configuration, sp.GetService<IApmLogger>(), ctx.HostingEnvironment.EnvironmentName));
}
else
{
Expand All @@ -56,16 +55,21 @@ public static IHostBuilder UseElasticApm(this IHostBuilder builder, params IDiag
services.AddSingleton<IApmAgent, ApmAgent>(sp =>
{
if (Agent.IsConfigured) return Agent.Instance;

var apmAgent = new ApmAgent(sp.GetService<AgentComponents>());
Agent.Setup(sp.GetService<AgentComponents>());
return apmAgent;
return Agent.Instance;
});

if(Agent.IsConfigured && Agent.Config.Enabled)
if (subscribers != null && subscribers.Any() && Agent.IsConfigured) Agent.Subscribe(subscribers);

services.AddSingleton(sp => sp.GetRequiredService<IApmAgent>().Tracer);

var serviceProvider = services.BuildServiceProvider();
var agent = serviceProvider.GetService<IApmAgent>();

if (!(agent is ApmAgent apmAgent)) return;

if (!Agent.IsConfigured || !apmAgent.ConfigurationReader.Enabled) return;

if (subscribers != null && subscribers.Any() && Agent.IsConfigured)
apmAgent.Subscribe(subscribers);
});

return builder;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
using System.Threading.Tasks;
using System;
using System.Threading.Tasks;
using Elastic.Apm.DiagnosticSource;
using FluentAssertions;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using SampleConsoleNetCoreApp;
Expand All @@ -24,9 +27,76 @@ public async Task TwoHostBuildersNoException()
await Task.WhenAll(hostBuilder1.StopAsync(), hostBuilder2.StopAsync());
}

private static IHostBuilder CreateHostBuilder() =>
/// <summary>
/// Makes sure that <see cref="Agent.IsConfigured" /> is <code>true</code> after the agent is enabled through
/// <see cref="HostBuilderExtensions.UseElasticApm" />.
/// </summary>
[Fact]
public void IsAgentInitializedAfterUseElasticApm()
{
var _ = CreateHostBuilder().Build();
Agent.IsConfigured.Should().BeTrue();
}

/// <summary>
/// Makes sure that agent enables the <see cref="IDiagnosticsSubscriber" /> passed into
/// <see cref="HostBuilderExtensions.UseElasticApm" />.
/// </summary>
[Fact]
public void DiagnosticSubscriberWithUseElasticApm()
{
var fakeSubscriber = new FakeSubscriber();
fakeSubscriber.IsSubscribed.Should().BeFalse();

Host.CreateDefaultBuilder()
.ConfigureServices((context, services) => { services.AddHostedService<HostedService>(); })
.UseElasticApm(fakeSubscriber)
.Build();

fakeSubscriber.IsSubscribed.Should().BeTrue();
}

/// <summary>
/// Sets `enabled=false` and makes sure that <see cref="HostBuilderExtensions.UseElasticApm" /> does not turn on diagnostic
/// listeners.
/// </summary>
[Fact]
public void DiagnosticSubscriberWithUseElasticApmAgentDisabled()
{
var fakeSubscriber = new FakeSubscriber();
fakeSubscriber.IsSubscribed.Should().BeFalse();

Environment.SetEnvironmentVariable("ELASTIC_APM_ENABLED", "false");

try
{
Host.CreateDefaultBuilder()
.ConfigureServices((context, services) => { services.AddHostedService<HostedService>(); })
.UseElasticApm();
.UseElasticApm(fakeSubscriber)
.Build();

fakeSubscriber.IsSubscribed.Should().BeFalse();
}
finally
{
Environment.SetEnvironmentVariable("ELASTIC_APM_ENABLED", null);
}
}

private static IHostBuilder CreateHostBuilder() =>
Host.CreateDefaultBuilder()
.ConfigureServices((context, services) => { services.AddHostedService<HostedService>(); })
.UseElasticApm();

public class FakeSubscriber : IDiagnosticsSubscriber
{
public bool IsSubscribed { get; set; }

public IDisposable Subscribe(IApmAgent components)
{
IsSubscribed = true;
return null;
}
}
}
}

0 comments on commit 997d924

Please sign in to comment.