Skip to content

Commit

Permalink
Refactor usage of telemetry classes.
Browse files Browse the repository at this point in the history
  • Loading branch information
dgarciarubio committed Oct 16, 2024
1 parent fb1a345 commit d0028d4
Show file tree
Hide file tree
Showing 12 changed files with 114 additions and 133 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.0-rtm.24515.11" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.0-rc.2.24474.3" />
<PackageReference Include="Scalar.AspNetCore" Version="1.2.9" />
</ItemGroup>

Expand Down
Original file line number Diff line number Diff line change
@@ -1,32 +1,27 @@
using System.Diagnostics;
using AspNetCore.Examples.OpenTelemetry.Api.WeatherForecast.Services;
using System.Diagnostics;

namespace AspNetCore.Examples.OpenTelemetry.Api.WeatherForecast;
namespace AspNetCore.Examples.OpenTelemetry.Api.WeatherForecast.Endpoints;

internal static class WeatherForecastExtensions
internal static class Get
{
public static IServiceCollection AddWeatherForecast(this IServiceCollection services)
{
services.AddTelemetry<IWeatherForecastTelemetry, WeatherForecastTelemetry>();
return services;
}
public static readonly IReadOnlyList<string> _summaries =
[
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
];

public static IEndpointRouteBuilder MapWeatherForecast(this IEndpointRouteBuilder endpoints)
public static IEndpointRouteBuilder MapGet(this IEndpointRouteBuilder endpoints)
{
var summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

endpoints.MapGet("/weather-forecast", (IWeatherForecastTelemetry telemetry) =>
endpoints.MapGet("/weather-forecast", (ITelemetry telemetry) =>
{
using var activity = telemetry.ActivitySource.StartActivity(name: "weather_forecast.request", kind: ActivityKind.Internal);

var forecast = Enumerable.Range(1, 5).Select(index =>
new WeatherForecast
(
DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
Random.Shared.Next(-20, 55),
summaries[Random.Shared.Next(summaries.Length)]
_summaries[Random.Shared.Next(_summaries.Count)]
))
.ToArray();

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using AspNetCore.Examples.OpenTelemetry.Api.WeatherForecast.Endpoints;
using AspNetCore.Examples.OpenTelemetry.Api.WeatherForecast.Services;

namespace AspNetCore.Examples.OpenTelemetry.Api.WeatherForecast;

internal static class Extensions
{
public static IServiceCollection AddWeatherForecast(this IServiceCollection services)
{
services.AddTelemetry();
return services;
}

public static IEndpointRouteBuilder MapWeatherForecast(this IEndpointRouteBuilder endpoints)
{
endpoints.MapGet();
return endpoints;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using System.Diagnostics;
using System.Diagnostics.Metrics;

namespace AspNetCore.Examples.OpenTelemetry.Api.WeatherForecast.Services;

internal interface ITelemetry : ITelemetry<WeatherForecast>
{
Histogram<int> TemperatureC { get; }
}

internal class Telemetry : Telemetry<WeatherForecast>, ITelemetry
{
public Telemetry(ILoggerFactory loggerFactory, IMeterFactory meterFactory)
: base(loggerFactory, meterFactory)
{
TemperatureC = Meter.CreateHistogram<int>("temperature", unit: "ºC");
}

public Histogram<int> TemperatureC { get; }
}

internal static class TelemetryExtensions
{
public static IServiceCollection AddTelemetry(this IServiceCollection services)
{
services.AddSingleton<ITelemetry, Telemetry>();
services.AddOpenTelemetry()
.WithTracing(t => t.AddSource(Telemetry.CategoryName))
.WithMetrics(t => t.AddMeter(Telemetry.CategoryName));
return services;
}
}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<Sdk Name="Aspire.AppHost.Sdk" Version="9.0.0-rc.1.24511.1" />

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsAspireHost>true</IsAspireHost>
<UserSecretsId>07803cbc-2fc9-4959-be1b-91c073960aa2</UserSecretsId>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Aspire.Hosting.AppHost" Version="9.0.0-preview.4.24456.4" />
<PackageReference Include="System.Text.Json" Version="9.0.0-rtm.24515.6" />
<PackageReference Include="Aspire.Hosting.AppHost" Version="9.0.0-rc.1.24511.1" />
</ItemGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />

<PackageReference Include="Microsoft.Extensions.Http.Resilience" Version="9.0.0-preview.9.24503.1" />
<PackageReference Include="Microsoft.Extensions.ServiceDiscovery" Version="9.0.0-preview.4.24456.4" />
<PackageReference Include="Microsoft.Extensions.Http.Resilience" Version="9.0.0-preview.9.24507.7" />
<PackageReference Include="Microsoft.Extensions.ServiceDiscovery" Version="9.0.0-rc.1.24511.1" />
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.9.0" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.0-rtm.24515.6" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.9.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.0-rc.2.24473.5" />
</ItemGroup>

</Project>

This file was deleted.

44 changes: 36 additions & 8 deletions AspNetCore.Examples.OpenTelemetry.TelemetryExtensions/Telemetry.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,32 @@ public class Telemetry<TCategoryName> : ITelemetry<TCategoryName>, IDisposable

public static readonly string CategoryName = TypeNameHelper.GetTypeDisplayName(typeof(TCategoryName), includeGenericParameters: false, nestedTypeDelimiter: '.');

private Lazy<ILogger<TCategoryName>>? _logger;
private Lazy<ActivitySource>? _activitySource;
private Lazy<Meter>? _meter;

public Telemetry(ILoggerFactory loggerFactory, IMeterFactory meterFactory)
{
Logger = loggerFactory.CreateLogger<TCategoryName>();
ActivitySource = new ActivitySource(ActivitySourceOptions.Name, ActivitySourceOptions.Version, ActivitySourceOptions.Tags);
Meter = meterFactory.Create(MeterOptions);
_logger = new Lazy<ILogger<TCategoryName>>(() =>
loggerFactory.CreateLogger<TCategoryName>(),
isThreadSafe: true);
_activitySource = new Lazy<ActivitySource>(() =>
new ActivitySource(CategoryName, ActivitySourceOptions.Version, ActivitySourceOptions.Tags),
isThreadSafe: true);
_meter = new Lazy<Meter>(() =>
meterFactory.Create(new MeterOptions(CategoryName)
{
Version = MeterOptions.Version,
Tags = MeterOptions.Tags,
Scope = MeterOptions.Scope,
}),
isThreadSafe: true);
}

public ILogger<TCategoryName> Logger { get; }
public ActivitySource ActivitySource { get; }
public Meter Meter { get; }

public ILogger<TCategoryName> Logger => _logger?.Value ?? throw new ObjectDisposedException(nameof(Logger));
public ActivitySource ActivitySource => _activitySource?.Value ?? throw new ObjectDisposedException(nameof(ActivitySource));
public Meter Meter => _meter?.Value ?? throw new ObjectDisposedException(nameof(Meter));

protected virtual ActivitySourceOptions ActivitySourceOptions => new(CategoryName);
protected virtual MeterOptions MeterOptions => new(CategoryName);
Expand All @@ -32,9 +48,21 @@ protected virtual void Dispose(bool disposing)
{
if (disposing)
{
ActivitySource.Dispose();
Meter.Dispose();
Interlocked.Exchange(ref _logger, null);

var activitySource = Interlocked.Exchange(ref _activitySource, null);
if (activitySource?.IsValueCreated ?? false)
{
activitySource.Value.Dispose();
}

var meter = Interlocked.Exchange(ref _meter, null);
if (meter?.IsValueCreated ?? false)
{
meter.Value.Dispose();
}
}

disposedValue = true;
}
}
Expand Down
1 change: 1 addition & 0 deletions AspNetCore.Examples.OpenTelemetry.sln
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{A98F4720-450D-4CA0-B137-932A7FFA1F1A}"
ProjectSection(SolutionItems) = preProject
.editorconfig = .editorconfig
global.json = global.json
README.md = README.md
EndProjectSection
EndProject
Expand Down
5 changes: 5 additions & 0 deletions global.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"sdk": {
"version": "9.0.100-rc.2.24474.11"
}
}

0 comments on commit d0028d4

Please sign in to comment.