BlazorWasmOtel 0.1.3
dotnet add package BlazorWasmOtel --version 0.1.3
NuGet\Install-Package BlazorWasmOtel -Version 0.1.3
<PackageReference Include="BlazorWasmOtel" Version="0.1.3" />
<PackageVersion Include="BlazorWasmOtel" Version="0.1.3" />
<PackageReference Include="BlazorWasmOtel" />
paket add BlazorWasmOtel --version 0.1.3
#r "nuget: BlazorWasmOtel, 0.1.3"
#:package BlazorWasmOtel@0.1.3
#addin nuget:?package=BlazorWasmOtel&version=0.1.3
#tool nuget:?package=BlazorWasmOtel&version=0.1.3
Blazor WASM OpenTelemetry
A lightweight OpenTelemetry integration library for Blazor WebAssembly applications with first-class support for Azure Monitor.
Features
- 🚀 Easy Setup - Simple one-line configuration with
AddBlazorOpenTelemetry() - 📊 Automatic Instrumentation - Automatic tracing of fetch/HTTP requests and document load events
- 🔍 Custom Spans - Create custom spans and add attributes via C# API
- 🔗 Correlation IDs - Automatic correlation ID propagation for distributed tracing
- ☁️ Azure Monitor Ready - First-class support for Azure Application Insights
- 🎯 Page View Tracking - Built-in support for tracking page navigation
Installation
Add the library reference to your Blazor WebAssembly project:
dotnet add package BlazorWasmOtel
Or add a project reference if building from source:
dotnet add reference path/to/BlazorWasmOtel.csproj
Quick Start
Configuration Security: Never commit connection strings or sensitive endpoints to source control. See CONFIG.md for using gitignored local configuration files.
1. Configure OpenTelemetry in Program.cs
Note on Azure Monitor: Azure Monitor's OTLP support is evolving. This library provides a foundation for OTLP-based telemetry. For production Azure Monitor scenarios, verify the current OTLP endpoint and authentication requirements from Azure Monitor documentation.
For Azure Monitor:
using BlazorWasmOtel;
using Microsoft.JSInterop;
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");
// Configure OpenTelemetry for Azure Monitor
builder.Services.AddBlazorOpenTelemetryForAzureMonitor(
"InstrumentationKey=xxxxx;IngestionEndpoint=https://xxxxx.in.applicationinsights.azure.com/");
// Add HttpClient with correlation ID support
builder.Services.AddHttpClient("API", client =>
{
client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress);
}).AddCorrelationId();
builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>().CreateClient("API"));
var host = builder.Build();
// Initialize OpenTelemetry
var jsRuntime = host.Services.GetRequiredService<IJSRuntime>();
var otelOptions = host.Services.GetRequiredService<BlazorOpenTelemetryOptions>();
await jsRuntime.InitializeBlazorOpenTelemetryAsync(otelOptions);
await host.RunAsync();
For Custom OTLP Endpoint:
builder.Services.AddBlazorOpenTelemetry(options =>
{
options.ServiceName = "my-blazor-app";
options.ServiceVersion = "1.0.0";
options.Endpoint = "http://localhost:4318/v1/traces";
options.EnableFetchInstrumentation = true;
options.EnableDocumentLoad = true;
});
2. Use Telemetry in Components
@page "/counter"
@inject IBlazorTelemetry Telemetry
<h1>Counter</h1>
<p>Current count: @currentCount</p>
<button @onclick="IncrementCount">Click me</button>
@code {
private int currentCount = 0;
protected override async Task OnInitializedAsync()
{
// Track page view
await Telemetry.TrackPageViewAsync("Counter");
}
private async Task IncrementCount()
{
// Create custom span
var spanId = await Telemetry.StartSpanAsync("counter.increment",
new Dictionary<string, object>
{
{ "counter.value", currentCount }
});
try
{
currentCount++;
// Add attributes to span
if (spanId != null)
{
await Telemetry.AddSpanAttributesAsync(spanId,
new Dictionary<string, object>
{
{ "counter.new_value", currentCount }
});
}
}
finally
{
if (spanId != null)
{
await Telemetry.EndSpanAsync(spanId);
}
}
}
}
API Reference
Configuration
AddBlazorOpenTelemetry(Action<BlazorOpenTelemetryOptions> configure)
Registers OpenTelemetry services with custom configuration.
AddBlazorOpenTelemetryForAzureMonitor(string connectionString)
Registers OpenTelemetry services configured for Azure Monitor.
AddCorrelationId()
Adds correlation ID support to HttpClient via a delegating handler.
IBlazorTelemetry Interface
Task<string?> StartSpanAsync(string name, Dictionary<string, object>? attributes)
Starts a custom span and returns a span ID.
Task EndSpanAsync(string spanId, Dictionary<string, object>? attributes)
Ends a span identified by span ID.
Task AddSpanAttributesAsync(string spanId, Dictionary<string, object> attributes)
Adds attributes to an active span.
Task TrackPageViewAsync(string pageName, Dictionary<string, object>? attributes)
Tracks a page view event.
Task<string> GetCorrelationIdAsync()
Gets the current correlation ID for distributed tracing.
Task FlushAsync()
Forces all pending spans to be exported immediately.
Architecture
This library consists of two main components:
JavaScript Module (
blazor-otel.js): A bundled OpenTelemetry JS SDK with instrumentations- Built with esbuild from TypeScript/ES modules
- Includes fetch and document-load instrumentations
- Exports spans via OTLP over HTTP
C# Wrapper: IJSRuntime extensions and service registrations
IBlazorTelemetryinterface for custom telemetryCorrelationIdDelegatingHandlerfor automatic correlation ID propagationServiceCollectionExtensionsfor easy DI setup
Use Cases
Page Views
Track navigation and user journeys:
await Telemetry.TrackPageViewAsync("ProductDetails", new Dictionary<string, object>
{
{ "product.id", productId },
{ "category", category }
});
Custom Business Operations
Track important business operations:
var spanId = await Telemetry.StartSpanAsync("order.checkout");
try
{
await ProcessOrder();
await Telemetry.AddSpanAttributesAsync(spanId, new Dictionary<string, object>
{
{ "order.total", orderTotal },
{ "order.items", itemCount }
});
}
finally
{
await Telemetry.EndSpanAsync(spanId);
}
Distributed Tracing
Correlation IDs are automatically added to HttpClient requests:
// Correlation ID is automatically added to this request
var response = await httpClient.GetAsync("https://api.example.com/data");
Building from Source
# Clone the repository
git clone https://github.com/kolatts/blazor-wasm-otel.git
cd blazor-wasm-otel
# Build the JavaScript module
cd src/BlazorWasmOtel
npm install
npm run build
# Build the .NET solution
cd ../..
dotnet build
# Run the sample
cd samples/BlazorWasmOtel.Sample
dotnet run
Sample Application
The repository includes a sample Blazor WebAssembly application demonstrating:
- OpenTelemetry initialization
- Page view tracking
- Custom span creation
- Correlation ID propagation
- Integration with Azure Monitor
Run it with:
cd samples/BlazorWasmOtel.Sample
dotnet run
License
MIT
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
| Product | Versions 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. |
-
net10.0
- Microsoft.AspNetCore.Components.Web (>= 10.0.0)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 10.0.0)
- Microsoft.Extensions.Http (>= 10.0.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.