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

[Do not merge] [Asp.Net Core] Measure req/sec with instrumentation #5138

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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using Microsoft.AspNetCore.Mvc;

namespace TestAspNetCoreInstrumentationPerf.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()
{
return 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();
}
}
18 changes: 18 additions & 0 deletions TestAspNetCoreInstrumentationPerf/DiagnosticSourceListener.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
namespace TestAspNetCoreInstrumentationPerf;

public class DiagnosticSourceListener : IObserver<KeyValuePair<string, object?>>
{
public void OnCompleted()
{
}

public void OnError(Exception error)
{
}

public void OnNext(KeyValuePair<string, object?> value)
{
// do nothing
// Measure how much perf is impacted by simply subscribing to diagnostic source.
}
}
35 changes: 35 additions & 0 deletions TestAspNetCoreInstrumentationPerf/DiagnosticSourceObserver.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using System.Diagnostics;

namespace TestAspNetCoreInstrumentationPerf
{
internal sealed class DiagnosticSourceSubscriber : IObserver<DiagnosticListener>
{
private static readonly HashSet<string> DiagnosticSourceEvents = new()
{
"Microsoft.AspNetCore.Hosting.HttpRequestIn",
"Microsoft.AspNetCore.Hosting.HttpRequestIn.Start",
"Microsoft.AspNetCore.Hosting.HttpRequestIn.Stop",
"Microsoft.AspNetCore.Diagnostics.UnhandledException",
"Microsoft.AspNetCore.Hosting.UnhandledException",
};

private readonly Func<string, object?, object?, bool> isEnabled = (eventName, _, _)
=> DiagnosticSourceEvents.Contains(eventName);

public void OnCompleted()
{
}

public void OnError(Exception error)
{
}

public void OnNext(DiagnosticListener value)
{
if (value.Name == "Microsoft.AspNetCore")
{
_ = value.Subscribe(new DiagnosticSourceListener(), isEnabled);
}
}
}
}
10 changes: 10 additions & 0 deletions TestAspNetCoreInstrumentationPerf/InstrumentationOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
namespace TestAspNetCoreInstrumentationPerf;

public class InstrumentationOptions
{
public bool EnableTraceInstrumentation { get; set; }

public bool EnableMetricInstrumentation { get; set; }

public bool EnableDiagnosticSourceSubscription { get; set; }
}
45 changes: 45 additions & 0 deletions TestAspNetCoreInstrumentationPerf/MyExporter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// <copyright file="MyExporter.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>

using System.Text;
using OpenTelemetry;

internal class MyExporter<T> : BaseExporter<T>
where T : class
{
private readonly string name;

public MyExporter(string name = "MyExporter")
{
this.name = name;
}

public override ExportResult Export(in Batch<T> batch)
{
return ExportResult.Success;
}

protected override bool OnShutdown(int timeoutMilliseconds)
{
Console.WriteLine($"{this.name}.OnShutdown(timeoutMilliseconds={timeoutMilliseconds})");
return true;
}

protected override void Dispose(bool disposing)
{
Console.WriteLine($"{this.name}.Dispose({disposing})");
}
}
60 changes: 60 additions & 0 deletions TestAspNetCoreInstrumentationPerf/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
using System.Diagnostics;
using OpenTelemetry.Metrics;
using OpenTelemetry.Trace;
using TestAspNetCoreInstrumentationPerf;

var builder = WebApplication.CreateBuilder(args);

var instrumentationOptions = new InstrumentationOptions();
builder.Configuration.GetSection("InstrumentationOptions").Bind(instrumentationOptions);

// 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();

Console.WriteLine("EnableMetricInstrumentation: " + instrumentationOptions.EnableMetricInstrumentation);
Console.WriteLine("EnableTraceInstrumentation: " + instrumentationOptions.EnableTraceInstrumentation);
Console.WriteLine("EnableDiagnosticSourceSubscription: " + instrumentationOptions.EnableDiagnosticSourceSubscription);

if (instrumentationOptions.EnableMetricInstrumentation)
{
builder.Services.AddOpenTelemetry().WithMetrics(builder => builder.AddAspNetCoreInstrumentation().AddReader(new PeriodicExportingMetricReader(new MyExporter<Metric>("TestExporter"))));
}

if (instrumentationOptions.EnableTraceInstrumentation)
{
builder.Services.AddOpenTelemetry().WithTracing(builder => builder.AddAspNetCoreInstrumentation());
}

if (instrumentationOptions.EnableDiagnosticSourceSubscription)
{
ActivitySource.AddActivityListener(new ActivityListener
{
ShouldListenTo = source => source.Name == "Microsoft.AspNetCore",
Sample = (ref ActivityCreationOptions<ActivityContext> options) => ActivitySamplingResult.AllDataAndRecorded,
ActivityStarted = activity => { },
ActivityStopped = activity => { },
});

DiagnosticListener.AllListeners.Subscribe(new DiagnosticSourceSubscriber());
}

var app = builder.Build();

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

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Swashbuckle.AspNetCore" VersionOverride="6.4.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" VersionOverride="1.6.0-rc.1" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" VersionOverride="1.7.0-rc.1" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
@TestAspNetCoreInstrumentationPerf_HostAddress = http://localhost:5203

GET {{TestAspNetCoreInstrumentationPerf_HostAddress}}/weatherforecast/
Accept: application/json

###
12 changes: 12 additions & 0 deletions TestAspNetCoreInstrumentationPerf/WeatherForecast.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
namespace TestAspNetCoreInstrumentationPerf;

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; }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
14 changes: 14 additions & 0 deletions TestAspNetCoreInstrumentationPerf/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"InstrumentationOptions": {
"EnableTraceInstrumentation": false,
"EnableMetricInstrumentation": false,
"EnableDiagnosticSourceSubscription" : false
},
"AllowedHosts": "*"
}
Loading