Skip to content

Commit

Permalink
Rework ActivitySource and Instrument usage
Browse files Browse the repository at this point in the history
  • Loading branch information
danelson committed Feb 7, 2023
1 parent 4f7668d commit 813df21
Showing 1 changed file with 10 additions and 4 deletions.
14 changes: 10 additions & 4 deletions examples/AspNetCore/Controllers/WeatherForecastController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@

namespace Examples.AspNetCore.Controllers;

using System.Diagnostics;
using System.Diagnostics.Metrics;
using Examples.AspNetCore;
using Microsoft.AspNetCore.Mvc;

Expand All @@ -31,12 +33,16 @@ public class WeatherForecastController : ControllerBase
private static readonly HttpClient HttpClient = new();

private readonly ILogger<WeatherForecastController> logger;
private readonly Instrumentation instrumentation;
private readonly ActivitySource activitySource;
private readonly Counter<long> freezingDaysCounter;

public WeatherForecastController(ILogger<WeatherForecastController> logger, Instrumentation instrumentation)
{
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
this.instrumentation = instrumentation ?? throw new ArgumentNullException(nameof(instrumentation));

ArgumentNullException.ThrowIfNull(instrumentation);
this.activitySource = instrumentation.ActivitySource;
this.freezingDaysCounter = instrumentation.FreezingDaysCounter;
}

[HttpGet]
Expand All @@ -51,7 +57,7 @@ public IEnumerable<WeatherForecast> Get()

// Manually create an activity. This will become a child of
// the incoming request.
using var activity = this.instrumentation.ActivitySource.StartActivity("calculate forecast");
using var activity = this.activitySource.StartActivity("calculate forecast");

var rng = new Random();
var forecast = Enumerable.Range(1, 5).Select(index => new WeatherForecast
Expand All @@ -63,7 +69,7 @@ public IEnumerable<WeatherForecast> Get()
.ToArray();

// Count the freezing days
this.instrumentation.FreezingDaysCounter.Add(forecast.Count(f => f.TemperatureC < 0));
this.freezingDaysCounter.Add(forecast.Count(f => f.TemperatureC < 0));

this.logger.LogInformation(
"WeatherForecasts generated {count}: {forecasts}",
Expand Down

0 comments on commit 813df21

Please sign in to comment.