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

chore(webapi): Add Opentelemetry tracing and metrics to webapi #1202

Merged
merged 22 commits into from
Oct 21, 2024
Merged
Show file tree
Hide file tree
Changes from 15 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
Expand Up @@ -8,13 +8,21 @@

<ItemGroup>
<PackageReference Include="Azure.Identity" Version="1.13.0" />
<PackageReference Include="Azure.Monitor.OpenTelemetry.AspNetCore" Version="1.2.0" />
<PackageReference Include="FastEndpoints.Swagger" Version="5.29.0"/>
<PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.22.0"/>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.10" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="8.0.10" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.10" />
<PackageReference Include="Microsoft.Azure.AppConfiguration.AspNetCore" Version="8.0.0" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.3" />
<PackageReference Include="Npgsql.OpenTelemetry" Version="8.0.4" />
<PackageReference Include="OpenTelemetry" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.Http" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.Runtime" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.StackExchangeRedis" Version="1.9.0-beta.1" />
knuhau marked this conversation as resolved.
Show resolved Hide resolved
knuhau marked this conversation as resolved.
Show resolved Hide resolved
<PackageReference Include="Serilog.Sinks.ApplicationInsights" Version="4.0.0"/>
</ItemGroup>

Expand All @@ -25,4 +33,4 @@
<ProjectReference Include="..\Digdir.Tool.Dialogporten.GenerateFakeData\Digdir.Tool.Dialogporten.GenerateFakeData.csproj"/>
</ItemGroup>

</Project>
</Project>
53 changes: 42 additions & 11 deletions src/Digdir.Domain.Dialogporten.WebApi/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Reflection;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
using Azure.Monitor.OpenTelemetry.AspNetCore;
using Digdir.Domain.Dialogporten.Application;
using Digdir.Domain.Dialogporten.Application.Common.Extensions;
using Digdir.Domain.Dialogporten.Application.Common.Extensions.OptionExtensions;
Expand All @@ -21,23 +22,26 @@
using FluentValidation;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.AspNetCore.Authorization;
using Npgsql;
using NSwag;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;
using OpenTelemetry.Metrics;
using Serilog;
using Microsoft.Extensions.Options;

// Using two-stage initialization to catch startup errors.
var telemetryConfiguration = TelemetryConfiguration.CreateDefault();
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Warning()
.Enrich.FromLogContext()
.WriteTo.Console(formatProvider: CultureInfo.InvariantCulture)
.WriteTo.ApplicationInsights(
TelemetryConfiguration.CreateDefault(),
TelemetryConverter.Traces)
.WriteTo.ApplicationInsights(telemetryConfiguration, TelemetryConverter.Traces)
knuhau marked this conversation as resolved.
Show resolved Hide resolved
.CreateBootstrapLogger();

try
{
BuildAndRun(args);
BuildAndRun(args, telemetryConfiguration);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
Expand All @@ -49,7 +53,7 @@
Log.CloseAndFlush();
}

static void BuildAndRun(string[] args)
static void BuildAndRun(string[] args, TelemetryConfiguration telemetryConfiguration)
{
var builder = WebApplication.CreateBuilder(args);

Expand All @@ -58,9 +62,7 @@ static void BuildAndRun(string[] args)
.ReadFrom.Configuration(context.Configuration)
.ReadFrom.Services(services)
.Enrich.FromLogContext()
.WriteTo.ApplicationInsights(
services.GetRequiredService<TelemetryConfiguration>(),
TelemetryConverter.Traces));
.WriteTo.ApplicationInsights(telemetryConfiguration, TelemetryConverter.Traces));

builder.Configuration
.AddAzureConfiguration(builder.Environment.EnvironmentName)
Expand Down Expand Up @@ -91,7 +93,6 @@ static void BuildAndRun(string[] args)
.AddHttpContextAccessor()
.AddValidatorsFromAssembly(thisAssembly, ServiceLifetime.Transient, includeInternalTypes: true)
.AddAzureAppConfiguration()
.AddApplicationInsightsTelemetry()
.AddEndpointsApiExplorer()
.AddFastEndpoints()
.SwaggerDocument(x =>
Expand Down Expand Up @@ -125,10 +126,40 @@ static void BuildAndRun(string[] args)
.JwtBearerTokenSchemas?
.Select(z => z.WellKnown)
.ToList() ?? [])

// Auth
.AddDialogportenAuthentication(builder.Configuration)
.AddAuthorization();
.AddAuthorization()

// OpenTelemetry
.AddOpenTelemetry()
.ConfigureResource(resource => resource
.AddService(serviceName: builder.Environment.ApplicationName))
.WithTracing(tracing =>
{
if (builder.Environment.IsDevelopment())
{
tracing.SetSampler(new AlwaysOnSampler());
}

tracing.AddAspNetCoreInstrumentation(options =>
{
options.Filter = (httpContext) =>
!httpContext.Request.Path.StartsWithSegments("/health");
});

tracing.AddHttpClientInstrumentation();
tracing.AddNpgsql();
tracing.AddRedisInstrumentation(options => options.SetVerboseDatabaseStatements = true);
})
.WithMetrics(metrics =>
{
metrics.AddRuntimeInstrumentation();
});

if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("APPLICATIONINSIGHTS_CONNECTION_STRING")))
{
builder.Services.AddOpenTelemetry().UseAzureMonitor();
}
knuhau marked this conversation as resolved.
Show resolved Hide resolved

if (builder.Environment.IsDevelopment())
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public async Task FailIfSwaggerSnapshotDoesNotMatch()
// The order of the properties in the swagger.json file is not cross-platform deterministic.
// Running client.GetAsync("/swagger/v1/swagger.json"); on Windows and Mac will produce
// different ordering of the results (although the content is the same). So we force an
// alphabetical ordering of the properties to make the test deterministic.
// alphabetical ordering of the properties to make the test deterministic.
// Ref: https://github.com/digdir/dialogporten/issues/996
var orderedSwagger = SortJson(newSwagger);

Expand Down
Loading