Skip to content

Commit

Permalink
chore(webapi): Add Opentelemetry tracing and metrics to webapi (#1202)
Browse files Browse the repository at this point in the history
<!--- Provide a general summary of your changes in the Title above -->

## Description

Replace Application Insights tracing with Opentelemetry in the webapi

<!--- Describe your changes in detail -->

## Related Issue(s)

- #1101 

## Verification

- [x] **Your** code builds clean without any errors or warnings
- [x] Manual testing done (required)
- [ ] Relevant automated test added (if you find this hard, leave it and
we'll help out)
  • Loading branch information
knuhau authored Oct 21, 2024
1 parent 20c3d54 commit ec7e049
Show file tree
Hide file tree
Showing 4 changed files with 63 additions and 13 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
using Azure.Monitor.OpenTelemetry.AspNetCore;
using OpenTelemetry.Trace;
using Npgsql;
using OpenTelemetry.Metrics;
using OpenTelemetry.Resources;

namespace Digdir.Domain.Dialogporten.WebApi.Common.Extensions;

internal static class WebApplicationBuilderExtensions
{
public static WebApplicationBuilder ConfigureTelemetry(this WebApplicationBuilder builder)
{
builder.Services.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();
})
.WithMetrics(metrics =>
{
metrics.AddRuntimeInstrumentation();
});

if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("APPLICATIONINSIGHTS_CONNECTION_STRING")))
{
builder.Services.AddOpenTelemetry().UseAzureMonitor();
}
else
{
// Use Application Insights SDK for local development
builder.Services.AddApplicationInsightsTelemetry();
}

return builder;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,17 @@

<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="Npgsql.OpenTelemetry" Version="8.0.5" />
<PackageReference Include="OpenTelemetry.Instrumentation.Runtime" Version="1.9.0" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.3" />
<PackageReference Include="OpenTelemetry" Version="1.9.0" />
<PackageReference Include="Serilog.Sinks.ApplicationInsights" Version="4.0.0"/>
</ItemGroup>

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

</Project>
</Project>
19 changes: 8 additions & 11 deletions src/Digdir.Domain.Dialogporten.WebApi/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@
using Digdir.Domain.Dialogporten.Application.Common.Extensions;
using Digdir.Domain.Dialogporten.Application.Common.Extensions.OptionExtensions;
using Digdir.Domain.Dialogporten.Application.Externals.Presentation;
using Digdir.Domain.Dialogporten.WebApi.Common.Extensions;
using Digdir.Domain.Dialogporten.Infrastructure;
using Digdir.Domain.Dialogporten.WebApi;
using Digdir.Domain.Dialogporten.WebApi.Common;
using Digdir.Domain.Dialogporten.WebApi.Common.Authentication;
using Digdir.Domain.Dialogporten.WebApi.Common.Authorization;
using Digdir.Domain.Dialogporten.WebApi.Common.Extensions;
using Digdir.Domain.Dialogporten.WebApi.Common.Json;
using Digdir.Domain.Dialogporten.WebApi.Common.Swagger;
using Digdir.Library.Utils.AspNet;
Expand All @@ -26,18 +26,17 @@
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)
.CreateBootstrapLogger();

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

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

Expand All @@ -58,9 +57,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 All @@ -74,6 +71,8 @@ static void BuildAndRun(string[] args)

var thisAssembly = Assembly.GetExecutingAssembly();

builder.ConfigureTelemetry();

builder.Services
// Options setup
.ConfigureOptions<AuthorizationOptionsSetup>()
Expand All @@ -91,7 +90,6 @@ static void BuildAndRun(string[] args)
.AddHttpContextAccessor()
.AddValidatorsFromAssembly(thisAssembly, ServiceLifetime.Transient, includeInternalTypes: true)
.AddAzureAppConfiguration()
.AddApplicationInsightsTelemetry()
.AddEndpointsApiExplorer()
.AddFastEndpoints()
.SwaggerDocument(x =>
Expand Down Expand Up @@ -125,7 +123,6 @@ static void BuildAndRun(string[] args)
.JwtBearerTokenSchemas?
.Select(z => z.WellKnown)
.ToList() ?? [])

// Auth
.AddDialogportenAuthentication(builder.Configuration)
.AddAuthorization();
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

0 comments on commit ec7e049

Please sign in to comment.