Skip to content

Commit

Permalink
Remove ApmMiddleWare, only use DiagnosticSource listener for ASP.NET …
Browse files Browse the repository at this point in the history
…Core (#2231)
  • Loading branch information
Mpdreamz authored Dec 7, 2023
1 parent 2d20ed3 commit 238698f
Show file tree
Hide file tree
Showing 33 changed files with 397 additions and 436 deletions.
7 changes: 7 additions & 0 deletions ElasticApmAgent.sln
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Elastic.Apm.AzureFunctionAp
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Elastic.Apm.Profiling", "benchmarks\Elastic.Apm.Profiling\Elastic.Apm.Profiling.csproj", "{CB6B3BA6-9D16-4CDC-95C2-7680CF50747D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebApiExample", "sample\WebApiExample\WebApiExample.csproj", "{00A025F1-0A31-4676-AA06-1773FC9744ED}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -575,6 +577,10 @@ Global
{CB6B3BA6-9D16-4CDC-95C2-7680CF50747D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CB6B3BA6-9D16-4CDC-95C2-7680CF50747D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CB6B3BA6-9D16-4CDC-95C2-7680CF50747D}.Release|Any CPU.Build.0 = Release|Any CPU
{00A025F1-0A31-4676-AA06-1773FC9744ED}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{00A025F1-0A31-4676-AA06-1773FC9744ED}.Debug|Any CPU.Build.0 = Debug|Any CPU
{00A025F1-0A31-4676-AA06-1773FC9744ED}.Release|Any CPU.ActiveCfg = Release|Any CPU
{00A025F1-0A31-4676-AA06-1773FC9744ED}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down Expand Up @@ -677,6 +683,7 @@ Global
{09CE5AC1-01F6-48C8-B266-2F891C408051} = {C2378D3C-2BA8-410F-AEF7-547C411C71C7}
{50F14EA5-DF72-425B-81A6-C7D532D2DD07} = {09CE5AC1-01F6-48C8-B266-2F891C408051}
{CB6B3BA6-9D16-4CDC-95C2-7680CF50747D} = {2825A761-5372-4620-99AB-253AD953E8CD}
{00A025F1-0A31-4676-AA06-1773FC9744ED} = {3C791D9C-6F19-4F46-B367-2EC0F818762D}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {69E02FD9-C9DE-412C-AB6B-5B8BECC6BFA5}
Expand Down
16 changes: 16 additions & 0 deletions sample/WebApiExample/Controllers/ErrorController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using Microsoft.AspNetCore.Mvc;

namespace WebApiExample.Controllers;

[ApiController]
[Route("[controller]")]
public class ErrorController : ControllerBase
{
private readonly ILogger<ErrorController> _logger;

public ErrorController(ILogger<ErrorController> logger) => _logger = logger;

[HttpGet(Name = "GetError")]
public IEnumerable<WeatherForecast> Get() =>
throw new Exception("This exception triggers a 500");
}
29 changes: 29 additions & 0 deletions sample/WebApiExample/Controllers/WeatherForecastController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
using Microsoft.AspNetCore.Mvc;

namespace WebApiExample.Controllers;

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

private readonly ILogger<WeatherForecastController> _logger;

public WeatherForecastController(ILogger<WeatherForecastController> logger) => _logger = logger;

[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get() =>
Enumerable.Range(1, 5)
.Select(index => new WeatherForecast
{
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();

}
28 changes: 28 additions & 0 deletions sample/WebApiExample/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using Elastic.Apm.AspNetCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();
app.UseElasticApm(app.Configuration);

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();
12 changes: 12 additions & 0 deletions sample/WebApiExample/WeatherForecast.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
namespace WebApiExample;

public class WeatherForecast
{
public DateOnly Date { get; set; }

public int TemperatureC { get; set; }

public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);

public string? Summary { get; set; }
}
18 changes: 18 additions & 0 deletions sample/WebApiExample/WebApiExample.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.5"/>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0"/>
</ItemGroup>

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

</Project>
72 changes: 0 additions & 72 deletions src/integrations/Elastic.Apm.AspNetCore/ApmMiddleware.cs

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,21 @@

namespace Elastic.Apm.AspNetCore
{
public static class ApmMiddlewareExtension
public static class ApplicationBuilderExtensions
{
/// <summary>
/// Adds the Elastic APM Middleware to the ASP.NET Core pipeline.
/// Sets up ASP.NET Core instrumentation to be sent over to Elastic APM.
/// <para>
/// You can customize the agent by passing additional IDiagnosticsSubscriber components to this method.
/// Use this method if you want to control what tracing capability of the agent you would like to use
/// or in case you want to minimize the number of dependencies added to your application.
/// </para>
/// <para>
/// Please note that by default without additional parameters this method only enables ASP.NET Core
/// monitoring - e.g. database statements or outgoing HTTP calls won't be traced.
/// If you want to simply enable every tracing component without configuration please use the
/// UseAllElasticApm extension method from the Elastic.Apm.NetCoreAll package.
/// <code>UseAllElasticApm()</code> extension method from the <c>Elastic.Apm.NetCoreAll</c> package.
/// </para>
/// </summary>
/// <returns>The elastic apm.</returns>
/// <param name="builder">Builder.</param>
Expand All @@ -38,8 +42,8 @@ public static class ApmMiddlewareExtension
/// If no <see cref="Microsoft.Extensions.Configuration.IConfiguration" /> is passed to the agent then it will read configs from environment variables.
/// </param>
/// <param name="subscribers">
/// Specify which diagnostic source subscribers you want to connect. The
/// <see cref="AspNetCoreErrorDiagnosticsSubscriber" /> is by default enabled.
/// Specify which diagnostic source subscribers you want to connect.
/// <para>The <see cref="AspNetCoreDiagnosticSubscriber" /> will always be injected if not specified.</para>
/// </param>
public static IApplicationBuilder UseElasticApm(
this IApplicationBuilder builder,
Expand Down Expand Up @@ -80,11 +84,11 @@ params IDiagnosticsSubscriber[] subscribers

var subs = subscribers?.ToList() ?? new List<IDiagnosticsSubscriber>(1);

if (subs.Count == 0 || subs.All(s => s.GetType() != typeof(AspNetCoreErrorDiagnosticsSubscriber)))
subs.Add(new AspNetCoreErrorDiagnosticsSubscriber());
if (subs.Count == 0 || subs.All(s => s.GetType() != typeof(AspNetCoreDiagnosticSubscriber)))
subs.Add(new AspNetCoreDiagnosticSubscriber());

agent.Subscribe(subs.ToArray());
return builder.UseMiddleware<ApmMiddleware>(agent.Tracer, agent);
return builder;
}

private static string GetEnvironmentName(this IServiceProvider serviceProvider) =>
Expand Down

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -14,23 +14,22 @@ internal static class HttpRequestExtensions
internal static string ExtractRequestBody(this HttpRequest request, IConfiguration configuration, out bool longerThanMaxLength)
{
//Ensure the request Microsoft.AspNetCore.Http.HttpRequest.Body can be read multiple times
#pragma warning disable CS0162 // Unreachable code detected
request.EnableBuffering();

if (request.HasFormContentType)
{
var form = new AspNetCoreHttpForm(request.Form);
return form.AsSanitizedString(configuration, out longerThanMaxLength);
}
else
{
// allow synchronous reading of the request stream, which is false by default from 3.0 onwards.
// Reading must be synchronous as it can happen within a synchronous diagnostic listener method
var bodyControlFeature = request.HttpContext.Features.Get<IHttpBodyControlFeature>();
if (bodyControlFeature != null)
bodyControlFeature.AllowSynchronousIO = true;
// allow synchronous reading of the request stream, which is false by default from 3.0 onwards.
// Reading must be synchronous as it can happen within a synchronous diagnostic listener method
var bodyControlFeature = request.HttpContext.Features.Get<IHttpBodyControlFeature>();
if (bodyControlFeature != null)
bodyControlFeature.AllowSynchronousIO = true;

return RequestBodyStreamHelper.ToString(request.Body, out longerThanMaxLength);
}
return RequestBodyStreamHelper.ToString(request.Body, out longerThanMaxLength);
#pragma warning restore CS0162 // Unreachable code detected
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

namespace Elastic.Apm.NetCoreAll
{
public static class ApmMiddlewareExtension
public static class ApplicationBuilderExtensions
{
/// <summary>
/// Adds the Elastic APM Middleware to the ASP.NET Core pipeline and enables
Expand Down Expand Up @@ -45,7 +45,7 @@ public static class ApmMiddlewareExtension
public static IApplicationBuilder UseAllElasticApm(
this IApplicationBuilder builder,
IConfiguration configuration = null
) => AspNetCore.ApmMiddlewareExtension
) => AspNetCore.ApplicationBuilderExtensions
.UseElasticApm(builder, configuration,
new HttpDiagnosticsSubscriber(),
new SqlClientDiagnosticSubscriber(),
Expand Down
2 changes: 2 additions & 0 deletions src/profiler/elastic_apm_profiler/src/profiler/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -487,6 +487,8 @@ impl Profiler {
unsafe {
unknown.AddRef();
}

println!("hello world init");

let process_path = std::env::current_exe().map_err(|e| {
// logging hasn't yet been initialized so unable to log
Expand Down
Loading

0 comments on commit 238698f

Please sign in to comment.