Skip to main content

How to Send ASP.NET Core Logs, Traces and Metrics to the Aspire Dashboard with OpenTelemetry

· 13 min read
Jagdish Kumawat
Founder @ Dewiride

Four OpenTelemetry packages and one UseOtlpExporter() call send an ASP.NET Core app's logs, traces and metrics to the Aspire Dashboard. This guide adds them to a small .NET 10 app, sends it requests, and reads the result on the dashboard's Structured logs, Traces and Metrics pages.

OpenTelemetry is a cross-platform, open standard for collecting and emitting telemetry data: logs, which record individual operations, metrics such as a histogram of the request latency, and traces, which show where time is spent. OTLP, the OpenTelemetry Protocol, is how an app sends that data on. The Aspire Dashboard receives OTLP and shows it in your browser. Microsoft's guide says the dashboard visualizes telemetry from any app that sends telemetry by using OTLP, and that it is a developer visualization tool, not a production monitoring tool.

Syntax​

Syntax
builder.Logging.AddOpenTelemetry(logging => <logOptions>);

builder.Services.AddOpenTelemetry()
.ConfigureResource(resource => resource.AddService("<serviceName>"))
.WithTracing(tracing => tracing.<traceInstrumentation>)
.WithMetrics(metrics => metrics.<metricInstrumentation>)
.UseOtlpExporter();

And the address to send to, as a setting:

appsettings.Development.json (the setting)
"OTEL_EXPORTER_OTLP_ENDPOINT": "<endpoint>"
PartWhat it does
builder.Logging.AddOpenTelemetry(...)Adds an OpenTelemetry logger next to the app's other loggers, so every ILogger entry also becomes an OpenTelemetry log record
<logOptions>What each log record keeps. IncludeFormattedMessage = true keeps the finished message and IncludeScopes = true keeps log scopes. Both are false by default
builder.Services.AddOpenTelemetry()Adds the OpenTelemetry SDK's services to the app
<serviceName>The name the dashboard shows for the app
<traceInstrumentation>What becomes a span: AddAspNetCoreInstrumentation() for each request the app answers, AddHttpClientInstrumentation() for each call its HttpClient makes
<metricInstrumentation>The same two, for measurements such as how long requests take
UseOtlpExporter()Sends logs, metrics and traces over OTLP
<endpoint>Where OTLP goes: the dashboard's OTLP address, http://localhost:4317 for gRPC

The OTLP exporter package's documentation: UseOtlpExporter Uses OpenTelemetry Protocol (OTLP) exporter for all signals. It can only be called once, and it cannot be called in addition to signal-specific AddOtlpExporter methods.

The Example​

HelloTelemetry is an empty ASP.NET Core app with one endpoint, /hello?name=.... The endpoint writes a log entry, calls NuGet's service index at https://api.nuget.org/v3/index.json with HttpClient, and answers with a greeting. The call to NuGet gives each request's trace a second step to look at.

Prerequisites​

  • The .NET 10 SDK.

Step 1: Create the App​

Terminal
dotnet new web -n HelloTelemetry
cd HelloTelemetry
Output
The template "ASP.NET Core Empty" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/HelloTelemetry/HelloTelemetry.csproj:
Restore succeeded.

dotnet new web creates an app from the ASP.NET Core Empty template, and -n names the app and its folder. cd moves into that folder.

Step 2: Add the OpenTelemetry Packages​

Terminal
dotnet add package OpenTelemetry.Extensions.Hosting --version 1.21.0
dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol --version 1.21.0
dotnet add package OpenTelemetry.Instrumentation.AspNetCore --version 1.21.0
dotnet add package OpenTelemetry.Instrumentation.Http --version 1.21.0
PackageWhat it brings
OpenTelemetry.Extensions.HostingAddOpenTelemetry() for the app's services
OpenTelemetry.Exporter.OpenTelemetryProtocolThe OTLP exporter and UseOtlpExporter()
OpenTelemetry.Instrumentation.AspNetCoreSpans and metrics for the requests the app answers
OpenTelemetry.Instrumentation.HttpSpans and metrics for the calls HttpClient makes

Each command adds one package to the project file and restores it, and ends like the last one:

Output (the last lines of the last command)
info : PackageReference for package 'OpenTelemetry.Instrumentation.Http' version '1.21.0' added to file '/Users/you/source/HelloTelemetry/HelloTelemetry.csproj'.
info : Writing assets file to disk. Path: /Users/you/source/HelloTelemetry/obj/project.assets.json
log : Restored /Users/you/source/HelloTelemetry/HelloTelemetry.csproj (in 682 ms).

Step 3: Turn On Logs, Traces and Metrics​

Replace everything in Program.cs. Start with the logs:

Program.cs (logs)
using OpenTelemetry;
using OpenTelemetry.Metrics;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;

var builder = WebApplication.CreateBuilder(args);

// Logs: every ILogger entry goes to OpenTelemetry too, with its finished message.
builder.Logging.AddOpenTelemetry(logging =>
{
logging.IncludeFormattedMessage = true;
logging.IncludeScopes = true;
});

AddOpenTelemetry adds what the package's documentation calls an OpenTelemetry logger named 'OpenTelemetry'. The console logger stays, so the app's console keeps printing every entry too. IncludeFormattedMessage keeps the message with its values filled in, and IncludeScopes keeps any log scopes around the entry.

Then traces, metrics and the exporter:

Program.cs (traces, metrics and the exporter)
builder.Services.AddOpenTelemetry()
// The name the dashboard shows for this app.
.ConfigureResource(resource => resource.AddService("HelloTelemetry"))
// Traces: every request the app answers, and every HTTP call it makes.
.WithTracing(tracing => tracing
.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation())
// Metrics: how many requests, and how long they took.
.WithMetrics(metrics => metrics
.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation())
// Send all three over OTLP, to the address in OTEL_EXPORTER_OTLP_ENDPOINT.
.UseOtlpExporter();
  • AddService("HelloTelemetry") names the app. Every log entry, span and metric carries that name, and the dashboard groups them under it.
  • WithTracing turns on traces. AddAspNetCoreInstrumentation() records each request the app answers, and AddHttpClientInstrumentation() each call it makes.
  • WithMetrics turns on metrics from the same two sources: how many requests there were and how long they took.
  • UseOtlpExporter() sends all of it. The package's documentation: Calling this method automatically enables logging, metrics, and tracing.

Step 4: Add an Endpoint That Calls Another Service​

Add the rest of Program.cs:

Program.cs (the endpoint)
builder.Services.AddHttpClient();

var app = builder.Build();

app.MapGet("/hello", async (string name, HttpClient http, ILogger<Program> logger) =>
{
logger.LogInformation("Saying hello to {Name}", name);

// A call to another service, so the trace shows a second step.
using HttpResponseMessage response = await http.GetAsync("https://api.nuget.org/v3/index.json");

return $"Hello, {name}! NuGet answered {(int)response.StatusCode}.";
});

app.Run();

AddHttpClient() registers the HTTP client factory. It also registers a plain HttpClient, which is why the endpoint can take one as a parameter, and the factory logs every request its clients send. The endpoint logs a line with ILogger, calls NuGet, and answers with NuGet's status code.

Step 5: Point the App at the Dashboard​

Add the dashboard's OTLP address to appsettings.Development.json. This is the whole file:

appsettings.Development.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"OTEL_EXPORTER_OTLP_ENDPOINT": "http://localhost:4317"
}

Microsoft's guide: You can configure the OTLP exporter through APIs in code, environment variables, or application configuration. This one is application configuration, for the Development environment that dotnet run uses. The Aspire Dashboard takes OTLP over gRPC at http://localhost:4317 (aspire.dev).

http://localhost:4317 is also where the exporter sends when nothing is set: the package's documentation gives it as the default for gRPC, and gRPC is the default protocol. Setting it anyway shows where the telemetry goes, and it's the one line to change when the dashboard runs somewhere else.

Step 6: Start the Dashboard and the App​

Start the Aspire Dashboard and sign in to it. It runs without Docker, with the Aspire CLI, or in Docker. Then start the app:

Terminal
dotnet run
Output
Using launch settings from /Users/you/source/HelloTelemetry/Properties/launchSettings.json...
Building...
info: Microsoft.Hosting.Lifetime[14]
Now listening on: http://localhost:5239
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
Content root path: /Users/you/source/HelloTelemetry

dotnet run builds the app and starts it. Hosting environment: Development means appsettings.Development.json is in use. The app listens on port 5239 here, the port the template wrote into Properties/launchSettings.json. Your app's port will likely be different, so use the one your console prints. Microsoft's guide says the same: Use the port shown in your own console output, because it might differ from the examples in this article.

Step 7: Send Two Requests​

Leave the app running, and open a second terminal:

Terminal
curl -s "http://localhost:5239/hello?name=Asha"
Output
Hello, Asha! NuGet answered 200.
Terminal
curl -s "http://localhost:5239/hello?name=Ravi"
Output
Hello, Ravi! NuGet answered 200.

curl sends a request to the address and prints the answer. -s is its silent mode, which curl's manual describes as Do not show progress meter or error messages. You can also open the same addresses in a browser.

macOS-style terminal window titled Terminal — HelloTelemetry showing curl requests to the hello endpoint for Asha and Ravi, answered with Hello, Asha! NuGet answered 200. and Hello, Ravi! NuGet answered 200.

Step 8: Read the Logs​

In the dashboard, open Structured logs:

The Aspire Dashboard's Structured logs page showing ten entries from HelloTelemetry: Saying hello to Asha and four HttpClient entries for the call to api.nuget.org that link to trace 71786e0, then the same five for Ravi that link to trace d40a7d3.

Each request left five entries. The first is the endpoint's own, Saying hello to Asha. The other four come from the HttpClient: Start processing, Sending, Received HTTP response headers and End processing. The Trace column links each entry to the trace it belongs to, so all five of Asha's entries point to trace 71786e0. Times on the dashboard are UTC.

Step 9: Follow a Trace​

Open Traces:

The Aspire Dashboard's Traces page listing two HelloTelemetry: GET /hello traces with two spans each, 71786e0 at 11:44:27.114 AM taking 0.52 seconds and d40a7d3 at 11:44:27.770 AM taking 0.32 seconds.

Each request is one trace, named after the app and the request: HelloTelemetry: GET /hello. Asha's took 0.52 seconds and Ravi's 0.32, and each has two spans. Select Asha's trace:

The Aspire Dashboard's trace detail for HelloTelemetry: GET /hello at 11:44:27.114 AM, with the GET /hello span and below it an HTTP GET 200 span to api.nuget.org:443 whose bar runs almost the whole 0.52 seconds.

The request's span, GET /hello, holds a second one, HTTP GET 200 to api.nuget.org:443: the call to NuGet. Its bar covers almost the whole request. The HttpClient's last log entry has the exact time: End processing HTTP request after 506.9344ms - 200. So about 0.51 of the request's 0.52 seconds went to NuGet. Microsoft's guide explains the nesting: Processing an ASP.NET request creates a span. Making an HttpClient request is a span. By tracking each span's parent, you build a hierarchy of spans that you can visualize.

Step 10: Check a Metric​

Open Metrics, select HelloTelemetry, and then http.server.request.duration:

The Aspire Dashboard's Metrics page for HelloTelemetry with the http.server.request.duration instrument selected, described as Duration of HTTP server requests, and a graph of P50, P90 and P99 in seconds over the last 30 minutes with a single peak just after 11:40 AM.

The middle column lists the app's meters, from ASP.NET Core and from System.Net, with 16 instruments in all. http.server.request.duration is a histogram of how long requests took. Microsoft's guide: for histograms, the dashboard collects values into a series of buckets and graphs the P50, P90, and P99 percentiles.

I sent the two requests twice, a few minutes apart: the peak on this graph, just after 11:40 UTC, comes from the first time, and the logs and traces above are from the second, at 11:44:27 UTC.

Why Metrics Take Up to a Minute​

Traces and metrics leave the app on different schedules. OpenTelemetry's environment variable specification sets the defaults:

SettingWhat it setsDefault
OTEL_BSP_SCHEDULE_DELAYFor spans: Delay interval (in milliseconds) between two consecutive exports5000
OTEL_METRIC_EXPORT_INTERVALFor metrics: The time interval (in milliseconds) between the start of two export attempts60000

So a span waits up to about five seconds before it's sent, and a metric up to a minute. The .NET SDK reads both settings: its documentation says they're parsed during object construction, and gives 5000 as the default delay between two exports of spans.

The Complete File​

Program.cs
using OpenTelemetry;
using OpenTelemetry.Metrics;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;

var builder = WebApplication.CreateBuilder(args);

// Logs: every ILogger entry goes to OpenTelemetry too, with its finished message.
builder.Logging.AddOpenTelemetry(logging =>
{
logging.IncludeFormattedMessage = true;
logging.IncludeScopes = true;
});

builder.Services.AddOpenTelemetry()
// The name the dashboard shows for this app.
.ConfigureResource(resource => resource.AddService("HelloTelemetry"))
// Traces: every request the app answers, and every HTTP call it makes.
.WithTracing(tracing => tracing
.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation())
// Metrics: how many requests, and how long they took.
.WithMetrics(metrics => metrics
.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation())
// Send all three over OTLP, to the address in OTEL_EXPORTER_OTLP_ENDPOINT.
.UseOtlpExporter();

builder.Services.AddHttpClient();

var app = builder.Build();

app.MapGet("/hello", async (string name, HttpClient http, ILogger<Program> logger) =>
{
logger.LogInformation("Saying hello to {Name}", name);

// A call to another service, so the trace shows a second step.
using HttpResponseMessage response = await http.GetAsync("https://api.nuget.org/v3/index.json");

return $"Hello, {name}! NuGet answered {(int)response.StatusCode}.";
});

app.Run();

macOS-style code window titled Program.cs — HelloTelemetry showing the OpenTelemetry logger, AddOpenTelemetry with the HelloTelemetry service name, ASP.NET Core and HttpClient instrumentation for traces and metrics, UseOtlpExporter, and the hello endpoint that logs a line and calls api.nuget.org.

Common Mistakes​

MistakeWhat happensDo this instead
Calling UseOtlpExporter() and also a signal-specific AddOtlpExporter()The package's documentation: the AddOtlpExporter calls will result in a NotSupportedException being thrownUse one or the other
Calling UseOtlpExporter() twiceSubsequent calls will result in a NotSupportedException being thrownCall it once
Opening Metrics right after the first requestThe page stays empty: metrics are sent once a minute by defaultWait for the next export

FAQ​

Do the logs still go to the console?​

Yes. AddOpenTelemetry adds a logger next to the console's, and the app's console printed the same entries as before.

Can I send telemetry only when an endpoint is set?​

Aspire's own service defaults template does that. It calls UseOtlpExporter() only when OTEL_EXPORTER_OTLP_ENDPOINT has a value:

Extensions.cs (Aspire service defaults template, excerpt from aspire.dev)
var useOtlpExporter = !string.IsNullOrWhiteSpace(builder.Configuration["OTEL_EXPORTER_OTLP_ENDPOINT"]);

if (useOtlpExporter)
{
builder.Services.AddOpenTelemetry().UseOtlpExporter();
}

Can I use the Aspire Dashboard in production?​

Microsoft's guide calls it a developer visualization tool, not a production monitoring tool. The exporter isn't tied to it: UseOtlpExporter() sends to whatever OTLP endpoint the setting names.

Conclusion​

builder.Logging.AddOpenTelemetry turns the app's log entries into OpenTelemetry records, WithTracing and WithMetrics say which work to record, and UseOtlpExporter() sends all three to the address in OTEL_EXPORTER_OTLP_ENDPOINT. On the dashboard, one request became five log entries and a trace whose NuGet call took about 0.51 of its 0.52 seconds. Metrics follow on their own schedule, once a minute by default.

Additional Resources​