Skip to content

Commit

Permalink
[examples] Add manual activities and custom metrics to ASP.NET Core e…
Browse files Browse the repository at this point in the history
…xample
  • Loading branch information
danelson committed Feb 1, 2023
1 parent 074c019 commit 232ab2b
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 3 deletions.
21 changes: 19 additions & 2 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 Microsoft.AspNetCore.Mvc;

[ApiController]
Expand All @@ -24,16 +26,23 @@ public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching",
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching",
};

private static readonly HttpClient HttpClient = new();

private readonly ILogger<WeatherForecastController> logger;
private readonly ActivitySource activitySource;
private readonly Counter<int> counter;

public WeatherForecastController(ILogger<WeatherForecastController> logger)
public WeatherForecastController(ILogger<WeatherForecastController> logger, ActivitySource activitySource, Meter meter)
{
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
this.activitySource = activitySource ?? throw new ArgumentNullException(nameof(activitySource));
ArgumentNullException.ThrowIfNull(meter);

// Create a custom metric
this.counter = meter.CreateCounter<int>("weather.days.freezing", "The number of days where the temperature is below freezing");
}

[HttpGet]
Expand All @@ -45,6 +54,11 @@ public IEnumerable<WeatherForecast> Get()
// how dependency calls will be captured and treated
// automatically as child of incoming request.
var res = HttpClient.GetStringAsync("http://google.com").Result;

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

var rng = new Random();
var forecast = Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Expand All @@ -54,6 +68,9 @@ public IEnumerable<WeatherForecast> Get()
})
.ToArray();

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

this.logger.LogInformation(
"WeatherForecasts generated {count}: {forecasts}",
forecast.Length,
Expand Down
15 changes: 14 additions & 1 deletion examples/AspNetCore/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
// limitations under the License.
// </copyright>

using System.Diagnostics;
using System.Diagnostics.Metrics;
using System.Reflection;
using OpenTelemetry;
using OpenTelemetry.Exporter;
Expand All @@ -34,10 +36,13 @@
// Note: Switch between Console/OTLP by setting UseLogExporter in appsettings.json.
var logExporter = appBuilder.Configuration.GetValue<string>("UseLogExporter").ToLowerInvariant();

var instrumentationScopeName = appBuilder.Configuration.GetValue<string>("InstrumentationScopeName");
var version = Assembly.GetExecutingAssembly().GetName().Version?.ToString() ?? "unknown";

// Build a resource configuration action to set service information.
Action<ResourceBuilder> configureResource = r => r.AddService(
serviceName: appBuilder.Configuration.GetValue<string>("ServiceName"),
serviceVersion: Assembly.GetExecutingAssembly().GetName().Version?.ToString() ?? "unknown",
serviceVersion: version,
serviceInstanceId: Environment.MachineName);

// Configure OpenTelemetry tracing & metrics with auto-start using the
Expand All @@ -48,7 +53,11 @@
{
// Tracing

// Create an ActivitySource for custom instrumentation
// and ensure the TracerPprovider subscribes to it.
appBuilder.Services.AddSingleton(new ActivitySource(instrumentationScopeName, version));
builder
.AddSource(instrumentationScopeName)
.SetSampler(new AlwaysOnSampler())
.AddHttpClientInstrumentation()
.AddAspNetCoreInstrumentation();
Expand Down Expand Up @@ -98,7 +107,11 @@
{
// Metrics

// Create a Meter for custom instrumentation
// and ensure the MeterProvider subscribes to it.
appBuilder.Services.AddSingleton(new Meter(instrumentationScopeName, version));
builder
.AddMeter(instrumentationScopeName)
.AddRuntimeInstrumentation()
.AddHttpClientInstrumentation()
.AddAspNetCoreInstrumentation();
Expand Down
1 change: 1 addition & 0 deletions examples/AspNetCore/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"ParseStateValues": true
}
},
"InstrumentationScopeName": "Examples.AspNetCore",
"ServiceName": "otel-test",
"AllowedHosts": "*",
"UseTracingExporter": "console",
Expand Down

0 comments on commit 232ab2b

Please sign in to comment.