Skip to content

Commit

Permalink
Add OpenTelemetry to TodosApi (#2014)
Browse files Browse the repository at this point in the history
This adds the default OpenTelemetry configuration used by .NET Aspire ServiceDefaults - enable instrumentation for:
* AspNetCore
* HttpClient
* Runtime

and OTLP exporter.
  • Loading branch information
eerhardt authored Aug 19, 2024
1 parent 0ca291d commit 8937602
Show file tree
Hide file tree
Showing 9 changed files with 107 additions and 26 deletions.
1 change: 1 addition & 0 deletions build/dependencies.props
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,6 @@
<RazorSlicesVersion>0.7.0</RazorSlicesVersion>
<SystemCommandLineVersion>2.0.0-beta4.22272.1</SystemCommandLineVersion>
<MicrosoftCrankEventSourcesVersion>0.2.0-alpha.24114.2</MicrosoftCrankEventSourcesVersion>
<OpenTelemetryVersion>1.9.0</OpenTelemetryVersion>
</PropertyGroup>
</Project>
9 changes: 2 additions & 7 deletions src/BenchmarksApps/TodosApi/AppSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ internal class AppSettings
public bool SuppressDbInitialization { get; set; }
}

// Change to using ValidateDataAnnotations once https://github.com/dotnet/runtime/issues/77412 is complete
// Changing this to use the Options Validation source generator increases the app size significantly.
// See https://github.com/dotnet/runtime/issues/106366
internal class AppSettingsValidator : IValidateOptions<AppSettings>
{
public ValidateOptionsResult Validate(string? name, AppSettings options)
Expand Down Expand Up @@ -42,12 +43,6 @@ public static IServiceCollection ConfigureAppSettings(this IServiceCollection se
optionsBuilder.ValidateOnStart();
}

// Change to using ValidateDataAnnotations once https://github.com/dotnet/runtime/issues/77412 is complete
//services.AddOptions<AppSettings>()
// .BindConfiguration(nameof(AppSettings))
// .ValidateDataAnnotations()
// .ValidateOnStart();

return services;
}
}
1 change: 1 addition & 0 deletions src/BenchmarksApps/TodosApi/DatabaseHealthCheck.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Nanorm;
using Npgsql;

namespace TodosApi;
Expand Down
1 change: 1 addition & 0 deletions src/BenchmarksApps/TodosApi/DatabaseInitializer.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Microsoft.Extensions.Options;
using Nanorm;
using Npgsql;

namespace TodosApi;
Expand Down
88 changes: 88 additions & 0 deletions src/BenchmarksApps/TodosApi/Extensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using OpenTelemetry;
using OpenTelemetry.Metrics;
using OpenTelemetry.Trace;
using TodosApi;

namespace Microsoft.Extensions.Hosting;

public static class Extensions
{
public static IHostApplicationBuilder AddServiceDefaults(this IHostApplicationBuilder builder)
{
builder.ConfigureOpenTelemetry();

builder.AddDefaultHealthChecks();

return builder;
}

public static IHostApplicationBuilder ConfigureOpenTelemetry(this IHostApplicationBuilder builder)
{
builder.Logging.AddOpenTelemetry(logging =>
{
logging.IncludeFormattedMessage = true;
logging.IncludeScopes = true;
});

builder.Services.AddOpenTelemetry()
.WithMetrics(metrics =>
{
metrics.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation()
.AddRuntimeInstrumentation();
})
.WithTracing(tracing =>
{
tracing.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation();
});

builder.AddOpenTelemetryExporters();

return builder;
}

private static IHostApplicationBuilder AddOpenTelemetryExporters(this IHostApplicationBuilder builder)
{
var useOtlpExporter = !string.IsNullOrWhiteSpace(builder.Configuration["OTEL_EXPORTER_OTLP_ENDPOINT"]);

if (useOtlpExporter)
{
builder.Services.AddOpenTelemetry().UseOtlpExporter();
}

return builder;
}

public static IHostApplicationBuilder AddDefaultHealthChecks(this IHostApplicationBuilder builder)
{
builder.Services.AddHealthChecks()
// Add a default liveness check to ensure app is responsive
.AddCheck("self", () => HealthCheckResult.Healthy(), ["live"])
.AddCheck<DatabaseHealthCheck>("Database", timeout: TimeSpan.FromSeconds(2))
.AddCheck<JwtHealthCheck>("JwtAuthentication");

return builder;
}

public static WebApplication MapDefaultEndpoints(this WebApplication app)
{
// Adding health checks endpoints to applications in non-development environments has security implications.
// See https://aka.ms/dotnet/aspire/healthchecks for details before enabling these endpoints in non-development environments.
if (app.Environment.IsDevelopment())
{
// All health checks must pass for app to be considered ready to accept traffic after starting
app.MapHealthChecks("/health");

// Only health checks tagged with the "live" tag must pass for app to be considered alive
app.MapHealthChecks("/alive", new HealthCheckOptions
{
Predicate = r => r.Tags.Contains("live")
});
}

return app;
}
}
8 changes: 4 additions & 4 deletions src/BenchmarksApps/TodosApi/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@
builder.Logging.ClearProviders();
#endif

// Add service defaults
builder.AddServiceDefaults();

// Bind app settings from configuration & validate
builder.Services.ConfigureAppSettings(builder.Configuration, builder.Environment);

Expand All @@ -24,9 +27,6 @@
});

// Configure health checks
builder.Services.AddHealthChecks()
.AddCheck<DatabaseHealthCheck>("Database", timeout: TimeSpan.FromSeconds(2))
.AddCheck<JwtHealthCheck>("JwtAuthentication");

// Problem details
builder.Services.AddProblemDetails();
Expand All @@ -50,7 +50,7 @@

app.MapShortCircuit(StatusCodes.Status404NotFound, "/favicon.ico");

app.MapHealthChecks("/health");
app.MapDefaultEndpoints();

// Enables testing request exception handling behavior
app.MapGet("/throw", void () => throw new InvalidOperationException("You hit the throw endpoint"));
Expand Down
16 changes: 3 additions & 13 deletions src/BenchmarksApps/TodosApi/Todo.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
using System.ComponentModel.DataAnnotations;
using Nanorm.Npgsql;
using Npgsql;
using Nanorm;

namespace TodosApi;

internal sealed class Todo : IDataReaderMapper<Todo>, IValidatable
[DataRecordMapper]
internal sealed partial class Todo : IValidatable
{
public int Id { get; set; }

Expand All @@ -14,16 +14,6 @@ internal sealed class Todo : IDataReaderMapper<Todo>, IValidatable

public bool IsComplete { get; set; }

public static Todo Map(NpgsqlDataReader dataReader)
{
return !dataReader.HasRows ? new() : new()
{
Id = dataReader.GetInt32(dataReader.GetOrdinal(nameof(Id))),
Title = dataReader.GetString(dataReader.GetOrdinal(nameof(Title))),
IsComplete = dataReader.GetBoolean(dataReader.GetOrdinal(nameof(IsComplete)))
};
}

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (string.IsNullOrEmpty(Title))
Expand Down
1 change: 1 addition & 0 deletions src/BenchmarksApps/TodosApi/TodoApi.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using Nanorm;
using Npgsql;
using TodosApi;

Expand Down
8 changes: 6 additions & 2 deletions src/BenchmarksApps/TodosApi/TodosApi.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
<LangVersion>preview</LangVersion>
<UserSecretsId>b8ffb8d3-b768-460b-ac1f-ef267c954c85</UserSecretsId>
<PublishAot>true</PublishAot>
<OpenApiDocumentsDirectory>.\</OpenApiDocumentsDirectory>
Expand All @@ -16,12 +15,17 @@
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="$(MicrosoftAspNetCoreAppPackageVersion)" />
<PackageReference Include="Npgsql" Version="$(NpgsqlVersion80)" />
<PackageReference Include="Nanorm.Npgsql" Version="0.0.5" />
<PackageReference Include="Nanorm.Npgsql" Version="0.1.2" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="$(MicrosoftAspNetCoreAppPackageVersion)" />
<PackageReference Include="Microsoft.Extensions.ApiDescription.Server" Version="$(MicrosoftAspNetCoreAppPackageVersion)">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="$(OpenTelemetryVersion)" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="$(OpenTelemetryVersion)" />
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="$(OpenTelemetryVersion)" />
<PackageReference Include="OpenTelemetry.Instrumentation.Http" Version="$(OpenTelemetryVersion)" />
<PackageReference Include="OpenTelemetry.Instrumentation.Runtime" Version="$(OpenTelemetryVersion)" />
</ItemGroup>

<ItemGroup>
Expand Down

0 comments on commit 8937602

Please sign in to comment.