Elvia.Telemetry.AspNetCore 8.0.0

dotnet add package Elvia.Telemetry.AspNetCore --version 8.0.0
                    
NuGet\Install-Package Elvia.Telemetry.AspNetCore -Version 8.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Elvia.Telemetry.AspNetCore" Version="8.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Elvia.Telemetry.AspNetCore" Version="8.0.0" />
                    
Directory.Packages.props
<PackageReference Include="Elvia.Telemetry.AspNetCore" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Elvia.Telemetry.AspNetCore --version 8.0.0
                    
#r "nuget: Elvia.Telemetry.AspNetCore, 8.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Elvia.Telemetry.AspNetCore@8.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Elvia.Telemetry.AspNetCore&version=8.0.0
                    
Install as a Cake Addin
#tool nuget:?package=Elvia.Telemetry.AspNetCore&version=8.0.0
                    
Install as a Cake Tool

Elvia Telemetry logging

The goal is to use the standard .NET ecosystem for logging and OpenTelemetry for telemetry collection and export. Use ILogger<T> for application logs, System.Diagnostics activities for tracing and System.Diagnostics.Metrics for metrics. The package provides Elvia defaults, small logging helpers and compatibility APIs for existing applications rather than a separate logging model.

See the Elvia developer handbook for additional logging and telemetry guidance.

Quick reference

I want to... Use
Set up telemetry in an ASP.NET Core app builder.Services.AddStandardElviaOpenTelemetry() from Elvia.Telemetry.AspNetCore, plus app.AddStandardElviaAspnetMetrics() and app.MapMetrics(). See ASP.NET Core.
Set up telemetry in a worker or generic host builder.Services.AddStandardElviaOpenTelemetry() from Elvia.Telemetry.Worker. See Worker services.
Write a log message Inject ILogger<T> and use LogInformation, LogWarning and so on, with message templates.
Attach an object's properties to one log record logger.LogWithProperties(level, message, properties)
Attach properties to several log records using (logger.BeginPropertiesScope(properties)) { ... }
Log a custom event (Application Insights customEvents) logger.LogEvent(name, properties)
Log an exception with properties logger.LogException(exception, properties)
Time a piece of work as a span Inject ITelemetryInsightsLogger and use using var span = telemetryLogger.StartActiveSpan("Name");
Record an outgoing call that has already completed telemetryLogger.TrackDependency(...)
Continue a trace received from another process StartActiveSpan(name, kind, new ParentTrace(traceparent)). See Spans.
Create Prometheus-style metrics Elvia.Telemetry.Metrics.CreateCounter/CreateGauge/CreateHistogram. See Metrics.
Use my own ActivitySource or Meter Register it with .WithTracing(t => t.AddSource(...)) or .WithMetrics(m => m.AddMeter(...)). See Custom sources and meters.
Drop specific spans .WithTracing(t => t.RetainTelemetryWhere(...)). See Filtering.

Do not use TrackEvent, TrackTrace, TrackException or TrackSpan in new code; they are obsolete. See Logging migration.

Export threshold: application ILogger records are exported from Information. Framework and SDK categories (Microsoft*, System*, Azure*) are exported from Warning. Override this under Logging:OpenTelemetry:LogLevel; see Log level.

Setup

Add the package for your application type:

Package Setup namespace Use
Elvia.Telemetry Elvia.Telemetry.Worker Worker services and other hosts
Elvia.Telemetry.AspNetCore Elvia.Telemetry.AspNetCore ASP.NET Core applications

Shared APIs, including ITelemetryInsightsLogger, the ILogger helpers, Metrics and tracing filters, are in Elvia.Telemetry. Import only one setup namespace; importing both Elvia.Telemetry.AspNetCore and Elvia.Telemetry.Worker causes ambiguous-call errors (CS0121).

ASP.NET Core

using Elvia.Telemetry;
using Elvia.Telemetry.AspNetCore;

builder.Services.AddStandardElviaOpenTelemetry();

var app = builder.Build();

app.UseRouting();
app.AddStandardElviaAspnetMetrics(); // Request metrics, after routing
app.MapMetrics();                    // Exposes /metrics

Worker services

using Elvia.Telemetry;
using Elvia.Telemetry.Worker;

builder.Services.AddStandardElviaOpenTelemetry();

The worker setup starts a Prometheus listener on port 2112. See Worker metrics.

Options

AddStandardElviaOpenTelemetry() without arguments uses the default options. It configures logging, tracing and metrics with Elvia's default exporters. It returns an IOpenTelemetryBuilder, so standard OpenTelemetry extensions and Elvia extensions can still be added afterward. Use AddElviaOpenTelemetry() (see Manual setup) when you want to configure each provider and choose exporters yourself; it does not set up any exporters or defaults. Do not combine the two, and do not call UseElviaGrafana() or UseElviaAppInsights(...) after AddStandardElviaOpenTelemetry(); the exporters would be registered twice.

builder.Services.AddStandardElviaOpenTelemetry(options =>
{
	// Also export to Application Insights through the Azure Monitor exporter
	options.AppInsightsConnectionString = builder.Configuration["core:kv:appinsights:core:connection_string"];
	options.IgnoredRequestPaths.Add("/ready"); // ASP.NET Core only
	options.MetricsPort = 2112;                // Worker services only
});
Option Default Applies to
AppInsightsConnectionString Not set; only Grafana (OTLP) export Both
TelemetryInsightsLoggerLogLevel Information Both; only the legacy ITelemetryInsightsLogger log methods
IgnoredRequestPaths /metrics, /health, /healthz, /endpoints, /getScriptTag ASP.NET Core
MetricsPort 2112 Worker services

Configure options through the callback. The environment variables listed in Defaults and configuration configure the OTLP exporter or supply process and Kubernetes identity; they are read directly and do not bind the options object.

Log level

ILogger records are exported to OpenTelemetry with these defaults:

Category Exported from Why
Application categories (everything not listed below) Information Application logs, including LogEvent and LogWithProperties, are written on purpose.
Microsoft*, System*, Azure* Warning Framework and SDK categories produce most of the Information volume, such as every EF Core command, ASP.NET Core request start/finish and Azure SDK calls.

The categories are matched by prefix, so a category such as Microsoft.EntityFrameworkCore.Database.Command uses the Microsoft rule. Debug and Trace records are not exported unless configured.

Override the defaults under Logging:OpenTelemetry:LogLevel in appsettings.json. The most specific category wins, and configuration wins over the defaults for the same category:

{
	"Logging": {
		"OpenTelemetry": {
			"LogLevel": {
				"Microsoft.EntityFrameworkCore.Database.Command": "Information",
				"MyCompany.Orders.Noisy": "Warning"
			}
		}
	}
}
To... Set under Logging:OpenTelemetry:LogLevel
Export a framework category again, for example EF Core commands "Microsoft.EntityFrameworkCore.Database.Command": "Information"
Export all framework Information logs "Microsoft": "Information", "System": "Information", "Azure": "Information"
Reduce logs from part of the application "MyCompany.Orders.Noisy": "Warning"
Export only Warning and above, as before v8 "Default": "Warning"

The same settings can be supplied as environment variables, for example Logging__OpenTelemetry__LogLevel__Microsoft=Information, or in code:

using OpenTelemetry.Logs;

builder.Logging.AddFilter<OpenTelemetryLoggerProvider>("Microsoft.AspNetCore", LogLevel.Information);

Use the OpenTelemetry section. The defaults are provider-specific, so the general Logging:LogLevel section does not override them. It still controls other providers, such as the console.

The legacy logging methods on ITelemetryInsightsLogger use TelemetryInsightsLoggerLogLevel in the options callback, or the UseElvia argument, which defaults to Information. That setting does not apply to ILogger records.

Manual setup

For full control over provider setup and exporters, start from AddElviaOpenTelemetry() and add each provider and exporter yourself:

var appInsightsConnectionString = new AppInsightsConnectionString(
	builder.Configuration.EnsureHasValue("core:kv:appinsights:core:connection_string"));

builder.Services.AddElviaOpenTelemetry()
	.WithLogging(logs => logs.UseElvia(), options => options.UseElviaGrafana())
	.WithTracing(tracing => tracing.UseElviaGrafana())
	.WithMetrics(metrics => metrics.UseElvia());

// ...or export to both Grafana and Application Insights through OpenTelemetry:
builder.Services.AddElviaOpenTelemetry()
	.WithLogging(
		logs => logs.UseElvia(),
		options => options.UseElviaGrafana()
			.UseElviaAppInsights(appInsightsConnectionString))
	.WithTracing(
		tracing => tracing.UseElviaGrafana()
			.UseElviaAppInsights(appInsightsConnectionString))
	.WithMetrics(metrics => metrics.UseElvia());

Telemetry is configured through OpenTelemetry. Application Insights is an export target through the OpenTelemetry Azure Monitor exporter; the packages do not use the Application Insights SDK.

For Entra ID authentication, use the manual setup, install Azure.Identity and pass a TokenCredential to both exporter registrations:

using Azure.Identity;

var credential = new DefaultAzureCredential();

builder.Services.AddElviaOpenTelemetry()
	.WithLogging(
		logs => logs.UseElvia(),
		options => options.UseElviaGrafana()
			.UseElviaAppInsights(appInsightsConnectionString, credential))
	.WithTracing(tracing => tracing.UseElviaGrafana()
		.UseElviaAppInsights(appInsightsConnectionString, credential))
	.WithMetrics(metrics => metrics.UseElvia());

Disable local authentication on the Azure Monitor resource when Entra ID should be required; the connection string alone continues to use the exporter's default authentication behavior.

Microsoft recommends migrating Application Insights instrumentation to OpenTelemetry and the Azure Monitor exporter. See Microsoft's migration guide.

ASP.NET Core metrics

ASP.NET Core requests are traced automatically. The ASP.NET Core package also provides request metrics middleware and a Prometheus scrape endpoint. Add the middleware after routing, then map the endpoint:

using Elvia.Telemetry.AspNetCore;

app.UseRouting();
app.AddStandardElviaAspnetMetrics();
app.MapMetrics(); // Exposes /metrics

The middleware keeps the http_request_duration_seconds and http_requests_received_total metric names for existing dashboards. To collect ASP.NET Core's built-in semantic-convention metrics instead, enable its meter and omit AddStandardElviaAspnetMetrics():

builder.Services.AddStandardElviaOpenTelemetry()
	.WithMetrics(metrics => metrics.AddMeter("Microsoft.AspNetCore.Hosting"));

This includes http.server.request.duration and is exported through the configured metrics exporter.

Worker metrics

The Worker setup starts a Prometheus listener on port 2112 by default; set MetricsPort in the options callback to change it. Scrape http://<host>:2112/metrics. It binds to localhost outside Kubernetes and to all interfaces inside Kubernetes, so expose the port through the host or service as appropriate.

using Elvia.Telemetry;
using Elvia.Telemetry.Worker;

builder.Services.AddStandardElviaOpenTelemetry(options => options.MetricsPort = 2112);

Defaults and configuration

The default setup collects:

  • Traces from the service's own spans (StartActiveSpan and StartSpan), Azure.*, Elvia.* and HttpClient instrumentation, and incoming requests in ASP.NET Core. Elvia.* sources can be disabled with SkipElviaLibrariesTracing(). Other ActivitySource names must be added; see Custom sources and meters.
  • Azure Service Bus ActivitySource tracing is still experimental and disabled by the Azure SDK by default. Elvia enables it unless the Azure SDK AppContext switch or environment variable is already configured. To disable it, set AZURE_EXPERIMENTAL_ENABLE_ACTIVITY_SOURCE=false before startup, or call AppContext.SetSwitch("Azure.Experimental.EnableActivitySource", false) before telemetry registration and before creating Azure SDK clients. This setting affects Azure SDK tracing process-wide.
  • Successful outgoing Azure Service Bus, Storage and Event Hubs calls, and HTTP calls to Vault, are filtered. Error spans and received-message spans are retained. ASP.NET Core also ignores GET and HEAD requests to the configured health and metrics paths; see Filtering.
  • Elvia.* metrics, including metrics created with Elvia.Telemetry.Metrics. .NET runtime and process metrics are opt-in; see Metrics.
  • Resource attributes: service.name, service.namespace, service.version, app, k8s.pod.label.app, k8s.namespace.name, container.image.name (when available) and elvia.dotnet.version. The OpenTelemetry Collector supplies k8s.pod.name and deployment.environment.
  • ILogger records from application categories at Information and above, and from Microsoft*, System* and Azure* categories at Warning and above; see Log level. ITelemetryInsightsLogger has a separate Information default, configurable with TelemetryInsightsLoggerLogLevel or the UseElvia argument.

The standard setup selects the Grafana OTLP exporters by default and adds Azure Monitor exporters when AppInsightsConnectionString is set. Add sources, meters, filters, samplers or other instrumentation by calling WithTracing, WithMetrics or WithLogging on the returned builder:

using OpenTelemetry.Trace;

builder.Services.AddStandardElviaOpenTelemetry()
	.WithTracing(tracing => tracing
		.AddSource("MyCompany.Orders")
		.SetSampler<AlwaysOnSampler>())
	.WithMetrics(metrics => metrics.AddMeter("System.Runtime", "MyCompany.Orders"));

Outside Kubernetes, local OTLP metric export uses a 5-second interval. The ASP.NET Core Prometheus exporter caches scrape responses for 15 seconds in Kubernetes and does not cache them elsewhere.

The default local OTLP endpoint is http://localhost:4317. Set OTEL_EXPORTER_OTLP_ENDPOINT to use another endpoint. These process and deployment variables are also read:

Variable Purpose
OTEL_SERVICE_NAME Overrides the service name. Otherwise, Kubernetes uses ELVIA_APPLICATION_NAME; local runs use the last segment of the entry assembly name, lowercased. Locally, the preceding assembly segments form the lowercased service.namespace.
ELVIA_ENVIRONMENT Used with both Kubernetes service variables to detect Kubernetes mode; also controls Kubernetes-only metric behavior.
ELVIA_APPLICATION_NAME Required in Kubernetes; supplies the application/service name.
ELVIA_APPLICATION_NAMESPACE Required in Kubernetes; supplies service.namespace and k8s.namespace.name.
ELVIA_APPLICATION_IMAGE Optional in Kubernetes; supplies container.image.name when set, otherwise a missing-image placeholder is emitted.
KUBERNETES_SERVICE_HOST, KUBERNETES_SERVICE_PORT Both must be set along with ELVIA_ENVIRONMENT for Kubernetes detection.
AZURE_EXPERIMENTAL_ENABLE_ACTIVITY_SOURCE Enables or disables experimental Azure SDK activity tracing; set to false to opt out.

Known limitations

  • The Azure Monitor exporter currently applies a provider-wide rate limit of five traces per second by default. This also affects spans sent to other configured exporters. If you set an application sampler, configure it after adding the Azure Monitor exporter; sampling defaults can change with exporter versions.
  • The Prometheus exporters used by the Worker and ASP.NET Core packages are pre-release versions of the OpenTelemetry Prometheus exporters.

Usage

Logging

Use an injected ILogger<T> for application logs. Prefer standard structured logging with message templates for regular messages:

logger.LogInformation("Order {OrderId} processed", orderId);

To attach an object's properties to a single record, use LogWithProperties. Use LogEvent when the record should be exported as a custom event, and LogException to log an exception with properties:

using Elvia.Telemetry;
using Microsoft.Extensions.Logging;

logger.LogWithProperties(LogLevel.Information, "Order processed", new { OrderId = orderId });
logger.LogEvent("OrderProcessed", new { OrderId = orderId });
logger.LogException(exception, new { OrderId = orderId });

LogWithProperties takes a literal message, not a message template. LogEvent logs at Information and LogException logs at Error.

For properties shared by multiple records, use BeginPropertiesScope:

using (logger.BeginPropertiesScope(new { OrderId = orderId }))
{
	logger.LogInformation("Order processed");
}

The records keep the category and filtering from ILogger<T>, and application categories are exported from Information; see Log level. Property values are exported as-is, so remove secrets and personal data before passing them; see Data and privacy.

Spans

Inject ITelemetryInsightsLogger to create spans. StartActiveSpan makes the span current, so spans and logs created inside it, including HttpClient and Azure SDK calls, are nested under it:

using Elvia.Telemetry;
using Microsoft.Extensions.Logging;

public class OrderProcessor(ILogger<OrderProcessor> logger, ITelemetryInsightsLogger telemetryLogger)
{
	public async Task ProcessAsync(Order order)
	{
		using var span = telemetryLogger.StartActiveSpan("Process order");
		span.SetAttribute("order.id", order.Id);

		try
		{
			await SaveAsync(order);
			logger.LogInformation("Order {OrderId} processed", order.Id);
		}
		catch (Exception ex)
		{
			span.RecordException(ex);
			span.SetStatusError(ex.Message);
			throw;
		}
	}
}
  • StartActiveSpan and StartSpan default to TelemetrySpanKind.Internal. Use TelemetrySpanKind.Client for outgoing calls that are not already instrumented, and Producer/Consumer for messaging.
  • StartSpan creates a span without making it current. StartRootSpan starts a new trace. Use WithSpan to make a span current, and CurrentSpan to read it.
  • Spans stay Unset unless an error is set; SetStatusOk() is optional.
  • SetAttributes(object) adds the public properties of an object as attributes.
  • Use TrackDependency only to record an outgoing call that has already completed; it cannot make the span current during the call.

For work that crosses a process boundary without automatic propagation (for example, Kafka without Elvia.Edna.Events), pass the W3C traceparent value in the message. The CorrelationInfo.ParentId value can be stored as that header and supplied as a ParentTrace when the message is handled:

using (var span = telemetryLogger.StartActiveSpan("Publish order", TelemetrySpanKind.Producer))
{
	message.Headers["traceparent"] = span.CorrelationInfo.ParentId;
}

var parentTrace = new ParentTrace(message.Headers["traceparent"]);
using (var span = telemetryLogger.StartActiveSpan("Process order", TelemetrySpanKind.Consumer, parentTrace))
{
	// Process the message; child spans inherit this context.
}

Use normal nested StartActiveSpan scopes for work in the same process; pass ParentTrace only when restoring context received from another process. Traces through Azure Service Bus and Kafka are propagated automatically when using the latest version of Elvia.Edna.Events.

Custom sources and meters

You can also use System.Diagnostics.ActivitySource and System.Diagnostics.Metrics.Meter directly. Sources and meters whose names start with Elvia. are collected by default. Register other names on the builder returned by the setup method; otherwise their spans and metrics are not exported:

builder.Services.AddStandardElviaOpenTelemetry()
	.WithTracing(tracing => tracing.AddSource("MyCompany.Orders"))
	.WithMetrics(metrics => metrics.AddMeter("MyCompany.Orders"));

Spans from ITelemetryInsightsLogger use a source named after the service and need no registration.

Metrics

Elvia.Telemetry.Metrics creates Prometheus-style counters, gauges and histograms. It is collected by default and mirrors the commonly used parts of the prometheus-net Metrics API, so existing code can keep working after replacing using Prometheus; with using Elvia.Telemetry;:

using Elvia.Telemetry;

private static readonly Counter OrdersProcessed = Metrics.CreateCounter(
	"orders_processed_total", "Number of processed orders.", "status");

OrdersProcessed.WithLabels("ok").Inc();

In Kubernetes, these counters and histograms are held back after startup so Prometheus does not miss the first increase; see Metrics in Kubernetes. Instruments created directly on a Meter are not held back.

Built-in .NET runtime and process metrics are disabled by default. To opt in, add the System.Runtime meter:

builder.Services.AddStandardElviaOpenTelemetry()
	.WithMetrics(metrics => metrics.AddMeter("System.Runtime"));

This includes metrics such as dotnet.process.cpu.time, dotnet.process.memory.working_set, dotnet.gc.collections and dotnet.thread_pool.queue.length. See the complete .NET runtime metrics reference.

Viewing telemetry data

If data is exported to Grafana Cloud, access to logs is controlled by Label Based Access Control and you can only access logs from applications in systems or namespaces where you have system developer roles.

If data is exported to Application Insights, you can access the data in the Azure Portal as usual.

Data and privacy

Treat telemetry as externally exported application data. Properties passed to LogWithProperties, LogEvent, LogException, BeginPropertiesScope and the Track* methods are serialized and exported as-is. The OpenTelemetry logging setup includes scopes. Values are not redacted; remove secrets and personal data before logging. Serialized property values are limited to 10,000 characters, and serialization failures fall back to ToString() or [serialization failed]. Standard ILogger template arguments and scopes do not go through this package's serializer.

Exception messages and stack traces can contain sensitive data. ASP.NET Core and HttpClient instrumentation record exceptions by default. Dependency data, including values passed to TrackDependency, may contain full URLs, query strings or SQL. Review instrumentation and exported fields for your application before sending telemetry to a backend; remove or redact sensitive values before recording them. There is no built-in redaction hook. Message sanitization replaces control characters; it is not a privacy or redaction mechanism.

Filtering

Use RetainTelemetryWhere(...) to drop traces you do not want to export. Without it, ActivityFilter.DefaultRetainTelemetryWhere is used. Setting your own filter replaces the default, so call ActivityFilter.DefaultRetainTelemetryWhere(activity) from it, as below, to keep the defaults. If you call RetainTelemetryWhere more than once, a span is exported only if every predicate returns true. The order of the calls does not matter. With the manual setup, add other exporters after UseElviaGrafana() / UseElviaAppInsights(...).

The default filter always keeps spans with Error status. Successful outgoing calls to Azure Service Bus, Storage and Event Hubs, and HTTP calls to Vault, are dropped. Spans for received messages are kept, so the work done while processing a message stays part of its trace. This example adds a rule on top of the defaults:

using System.Diagnostics;
using Elvia.Telemetry;
using Elvia.Telemetry.Filter;

builder.Services.AddStandardElviaOpenTelemetry()
	.WithTracing(tracing => tracing.RetainTelemetryWhere(activity => activity switch
	{
		// Drop successful calls to a chatty internal dependency
		{ Kind: ActivityKind.Client, Status: not ActivityStatusCode.Error }
			when activity.GetTagItem("server.address")?.ToString() == "internal-cache" => false,
		_ => ActivityFilter.DefaultRetainTelemetryWhere(activity)
	}));

With the manual setup, call RetainTelemetryWhere(...) on the same tracing builder as UseElviaGrafana() / UseElviaAppInsights(...).

Default ASP.NET Core filtering already ignores GET and HEAD requests to the following paths, and to paths below them (for example /health/ready). Matching is case-insensitive:

  • /metrics
  • /health
  • /healthz
  • /endpoints
  • /getScriptTag

With the standard setup, add paths through IgnoredRequestPaths in the options callback.

By default, tracing includes AddSource("Elvia.*") to collect spans from other Elvia libraries (for example Elvia.Edna.Events). If you want only your own service spans and explicitly configured sources, opt out with SkipElviaLibrariesTracing():

builder.Services.AddStandardElviaOpenTelemetry()
	.WithTracing(tracing => tracing.SkipElviaLibrariesTracing());

Metrics in Kubernetes

In Kubernetes, counters and histograms are held back after start. Prometheus computes rate() and increase() from the difference between two readings, so a series that first appears with a value above 0 loses that first increase. To avoid this, call Inc(0) on a counter at startup. The series then starts at 0, and the real increases are written once Prometheus has scraped that 0: shortly after the first scrape of /metrics, and at the latest one minute after start. Counter increases made in the meantime are not lost, only delayed. Each held-back histogram series buffers up to 10,000 observations; additional observations for that series are dropped until it goes live. Gauges are never held back, and nothing is held back outside Kubernetes.

A series with label values that first occur after startup is not protected by this. If the first increase matters for such a series, enable start timestamps in Prometheus (--enable-feature=created-timestamp-zero-ingestion). The exporter writes _created for OpenMetrics.

Upgrade to v8.0

These changes can affect existing code or the data you see in your backends.

The migration favors standard .NET logging and OpenTelemetry instrumentation. Existing applications can keep the supported compatibility APIs where needed; new application logs should use the application's ILogger<T> so that categories, filtering and providers work consistently with the rest of .NET.

See also the v8 release notes.

Setup methods

The standard setup is now AddStandardElviaOpenTelemetry(). AddElviaOpenTelemetry() still returns a builder without exporters for manual setup, as in v7; code that configures exporters with WithLogging, WithTracing and WithMetrics keeps working.

  • The AddElviaOpenTelemetry(config) overload was removed. The v7 config type was empty, so remove the argument and keep the manual setup, or switch to AddStandardElviaOpenTelemetry(config) and remove the UseElviaGrafana()/UseElviaAppInsights(...) calls, which the standard setup already adds.

Namespaces

The ASP.NET Core API moved to Elvia.Telemetry.AspNetCore. In v7, AddElviaOpenTelemetry and the provider builder extensions (UseElvia, UseElviaGrafana, UseElviaAppInsights) were in Elvia.Telemetry, and AddStandardElviaAspnetMetrics and MapMetrics were in Elvia.Telemetry.Extensions. The method names are unchanged, so the only change is the using directive:

Package Remove Add
Elvia.Telemetry.AspNetCore using Elvia.Telemetry.Extensions; using Elvia.Telemetry.AspNetCore; (keep using Elvia.Telemetry; for shared types)
Elvia.Telemetry (workers) using Elvia.Telemetry.Worker; (as before)

Shared types such as ITelemetryInsightsLogger, Metrics, AppInsightsConnectionString, RetainTelemetryWhere and SkipElviaLibrariesTracing stay in Elvia.Telemetry; ActivityFilter is in Elvia.Telemetry.Filter. Importing both Elvia.Telemetry.AspNetCore and Elvia.Telemetry.Worker gives a compile error (CS0121), which prevents getting the wrong variant by accident.

ITelemetrySpan, ParentTrace and TelemetrySpanLink are also in Elvia.Telemetry. Update code that used these types from the global namespace to add using Elvia.Telemetry;.

The legacy IInstrumentationMode, ApplicatonInsightsInstrumentationMode, IsAlreadyRegisteredWithAnotherMode and ElviaDefaultTracesFilterProcessor APIs were removed. The empty OpenTelemetryBuilderExtensions types were removed as well. ITelemetry and the obsolete AddStandardElviaTelemetryLogging* migration stubs remain.

Filtering changes

  • The default filter now always keeps spans with status Error. Successful spans have status Unset, so successful outgoing calls to Azure Service Bus, Storage and Event Hubs and HTTP calls to Vault are now dropped as intended. Earlier versions kept almost everything. Spans for received Service Bus messages are kept.
  • RetainTelemetryWhere replaces the default filter, and several calls are combined so that every predicate must return true. The order of the calls no longer matters. It requires UseElviaGrafana() or UseElviaAppInsights(...), and other exporters must be added after them. See Filtering.
  • ASP.NET Core requests to /metrics, /health, /healthz, /endpoints and /getScriptTag are now ignored for GET and HEAD, case-insensitively and including paths below them (for example /health/ready, /metrics/). Earlier versions only ignored GET with an exact, case-sensitive path.
Dropping received Service Bus messages

Spans for received Service Bus messages (ActivityKind.Consumer) are kept by default, because they are the root of the work done while processing a message. If you do not want them, add a rule on top of the defaults:

.RetainTelemetryWhere(activity => activity switch
{
	{ Kind: ActivityKind.Consumer, Status: not ActivityStatusCode.Error }
		when activity.GetTagItem("az.namespace")?.ToString() == "Microsoft.ServiceBus" => false,
	_ => ActivityFilter.DefaultRetainTelemetryWhere(activity)
})

Only the received-message span is dropped. Spans created while handling the message (database calls, HTTP calls, your own spans) are not, and they are exported without their parent. To drop those as well, add rules for them, or filter on what the handler does rather than on the received message.

Metrics changes

  • In Kubernetes, held-back counter increases and histogram observations are now written shortly after the first scrape of /metrics instead of after a fixed minute (the minute is the fallback). See Metrics in Kubernetes.
  • While held back, each histogram label series buffers up to 10,000 observations. Additional observations for that series are dropped until it goes live.
  • Counter.Inc accepts double values. Negative increments now throw ArgumentOutOfRangeException; use a gauge for values that can decrease.
  • The ASP.NET Core middleware maps non-standard HTTP methods to _OTHER in the method metric label, keeping label cardinality bounded.
  • The worker UseElvia extension is in Elvia.Telemetry.Worker; the ASP.NET Core setup and extensions are in Elvia.Telemetry.AspNetCore. This prevents the old same-name extension collisions between the two packages.

Span changes

  • Spans created through ITelemetryInsightsLogger (StartActiveSpan, StartSpan, CurrentSpan) are no longer set to status Ok. They stay Unset unless an error is set, and reading CurrentSpan no longer overwrites an error set by ASP.NET Core or HttpClient. SetStatusOk() is optional.
  • TrackSpan remains available with an obsolete warning and continues to create Client spans. Use StartActiveSpan or StartSpan to choose the span kind.
  • StartActiveSpan makes the span current; StartSpan does not. Both default to TelemetrySpanKind.Internal, appropriate for work within the application. When replacing TrackSpan, use StartActiveSpan with TelemetrySpanKind.Client to preserve its active client-span behavior, and attach properties with SetAttribute.
  • TrackDependency remains supported and is not obsolete. It records an already completed outgoing call as a client span, treating the registration time as the end and subtracting the supplied duration for the start. Use StartActiveSpan with TelemetrySpanKind.Client when you can instrument around the call itself; after-the-fact registration cannot make the span current during the original call.
  • When both Grafana and Application Insights exporters are configured, Elvia resource attributes (for example app and Kubernetes metadata) are now consistently included on spans sent to Grafana.
  • service.version comes from the assembly informational version. The OpenTelemetry Collector supplies k8s.pod.name and deployment.environment; this package supplies k8s.namespace.name. The Elvia-specific app and k8s.pod.label.app attributes remain aliases for the service name for dashboard compatibility.
  • The package no longer supplies the old k8s.pod.label.name attribute, which incorrectly contained the machine name.
  • Locally, the default service.name is the last segment of the entry assembly name, lowercased, and service.namespace is the lowercased preceding assembly prefix; OTEL_SERVICE_NAME takes precedence for the name. The local k8s.namespace.name remains localhost. Kubernetes resource naming is unchanged and uses ELVIA_APPLICATION_NAME and ELVIA_APPLICATION_NAMESPACE when the Kubernetes service variables and ELVIA_ENVIRONMENT identify the process as running in Kubernetes.

Logging migration

TrackEvent, TrackException and TrackTrace remain for compatibility but are obsolete. Inject ILogger<T> and use standard logging methods or the extensions in Elvia.Telemetry:

Old call Replacement
telemetry.TrackEvent(name, properties) logger.LogEvent(name, properties)
telemetry.TrackException(exception, properties) logger.LogException(exception, properties)
telemetry.TrackTrace(message, properties) logger.LogWithProperties(LogLevel.Information, message, properties)

LogEvent logs at Information with the microsoft.custom_event.name attribute, preserving Azure Monitor custom-event export. LogException logs at Error and preserves the exception. LogWithProperties takes a literal message, not a message template. These helpers retain property serialization and message sanitization from the old methods while using the caller's logger category.

If a TrackTrace call specifies a severity, map Verbose to LogLevel.Debug, and Information, Warning, Error and Critical to the corresponding LogLevel. The existing mapping is preserved; ILogger.LogTrace is not a direct replacement. suppressTelemetry: true means the old call does not log anything; keep that condition around the replacement call if needed.

Check log filtering when migrating. The helpers use the caller's category instead of the legacy logger category, so they follow the ILogger export defaults: Information for application categories and Warning for Microsoft*, System* and Azure* categories. If the calling class is in such a namespace, or Logging:OpenTelemetry:LogLevel raises the level for its category, adjust the configuration as shown in Log level. TelemetryInsightsLoggerLogLevel only controls the legacy logger.

Log level defaults

v7 exported ILogger records only from Warning, following the old Application Insights SDK default. v8 exports application categories from Information and keeps Warning for Microsoft*, System* and Azure* categories. Applications that log a lot at Information will export more data, which can increase Application Insights cost. To keep the v7 behavior, set Logging:OpenTelemetry:LogLevel:Default to Warning; see Log level.

For regular messages, prefer standard structured logging, for example logger.LogInformation("Order {OrderId} processed", orderId). Use the helpers for attaching an object to one record and BeginPropertiesScope for context shared by several records; see Logging.

Logging properties

DictionarySerializer is now internal. Applications that used it directly must use their own serializer. Properties passed to TrackEvent, TrackException or TrackTrace are exported as-is and are not redacted; remove secrets and personal data before passing them. Each value is limited to 10,000 characters, and values that cannot be JSON-serialized fall back to ToString() or [serialization failed].

ConsoleWriter and IPropertiesLogger were removed. The writeToConsole path is no longer available; the obsolete AddStandardElviaTelemetryLogging* stubs remain only to provide migration diagnostics.

Internal types

ServiceCollectionBase and the MetricTrackingService implementation are now internal. Keep using IMetricTrackingService from dependency injection; it is still registered by the setup methods. BufferBase and CacheByLabelValues<T> remain public base types, but their constructors are no longer available to external callers. Histogram.Child and related metric child types remain public.

Upgrade to v6.0

From v5 to v6 of Elvia.Telemetry and Elvia.Telemetry.AspNetCore, these main things changed:

  1. We stopped using the NuGet package prometheus-net and now use built-in System.Diagnostics.Metrics.
  2. OpenTelemetry is now the telemetry pipeline.
  3. All counters are suffixed with _total if missing. Ensure dashboards and alerts are updated.

Change from prometheus-net to System.Diagnostics.Metrics

To make the transition easier, we added an in-place wrapper for the static type Prometheus.Metrics. The new type is Elvia.Telemetry.Metrics. This means you can continue to use the same code as before, but it will now use System.Diagnostics.Metrics.

Do this:

  1. Remove the NuGet package prometheus-net.
  2. Replace all using Prometheus; with using Elvia.Telemetry;.

Rewrite from AddStandardElviaTelemetryLogging to AddStandardElviaOpenTelemetry

AddStandardElviaTelemetryLogging* has been phased out and is no longer supported. Replace it with AddStandardElviaOpenTelemetry(), or with AddElviaOpenTelemetry() if you configure exporters yourself.

Relevant migration notes:

  • retainTelemetryWhere on the old API is replaced by RetainTelemetryWhere(...) on tracing.
  • Filtering of /metrics and /health is already included by default for ASP.NET Core tracing.
  • Adaptive sampling from the old Application Insights SDK is no longer available.
  • If sampling is needed, configure an OpenTelemetry sampler such as SetSampler<AlwaysOnSampler>() or another OpenTelemetry sampler.

Local development

Run either the Aspire Dashboard or Grafana LGTM locally. With the default OTLP endpoint, telemetry is sent to http://localhost:4317.

Aspire Dashboard

The Aspire Dashboard is available as a Docker image.

docker run --rm --name aspire-dashboard -p 18888:18888 -p 4317:18889 -p 4318:18890 -e DOTNET_DASHBOARD_UNSECURED_ALLOW_ANONYMOUS=true mcr.microsoft.com/dotnet/aspire-dashboard:13

Open http://localhost:18888. Stop it with Ctrl+C.

Grafana LGTM

docker run --rm --name otel-lgtm -p 3000:3000 -p 4317:4317 -p 4318:4318 grafana/otel-lgtm:latest

Open Grafana at http://localhost:3000. Stop the container with Ctrl+C. For image options and details, see the Grafana OTEL-LGTM project.

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (3)

Showing the top 3 NuGet packages that depend on Elvia.Telemetry.AspNetCore:

Package Downloads
Elvia.Mdmx.Apps.Shared

Shared library for MDMx applications.

Elvia.Elvid.Bff.UserClient

Package Description

Elvia.PushReceiverCore

Core functionality for implementing a dotnet core based Push Receiver.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
8.0.0 302 11/16/2026
8.0.0-rc5 63 11/13/2026
8.0.0-rc4 82 11/13/2026
8.0.0-rc3 54 11/12/2026
8.0.0-rc1 47 11/12/2026
8.0.0-preview.1-7 56 11/14/2026
8.0.0-preview.1-6 49 11/16/2026
8.0.0-preview.1-5 55 11/9/2026
8.0.0-preview.1-4 66 10/30/2026
8.0.0-preview.1-3 75 10/29/2026
8.0.0-preview.1-2 66 10/23/2026
8.0.0-preview.1-1 66 10/21/2026
8.0.0-beta2 67 10/13/2026
8.0.0-beta1 66 10/13/2026
7.3.3-preview.1-9 64 10/13/2026
7.3.3-preview.1-8 68 10/11/2026
7.3.3-preview.1-7 68 10/9/2026
7.3.3-preview.1-6 88 9/25/2026
7.3.3-preview.1-5 69 9/22/2026
7.3.3-preview.1-4 84 9/20/2026
Loading failed