Skip to content

.NET

Instrument your .NET applications to send traces, logs, and metrics to Kopai.

Terminal window
dotnet add package OpenTelemetry.Extensions.Hosting
dotnet add package OpenTelemetry.Instrumentation.AspNetCore
dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol

Add OpenTelemetry to your ASP.NET Core application:

using OpenTelemetry.Exporter;
using OpenTelemetry.Logs;
using OpenTelemetry.Metrics;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;
var builder = WebApplication.CreateBuilder(args);
var endpoint = Environment.GetEnvironmentVariable("OTEL_EXPORTER_OTLP_ENDPOINT")
?? "http://localhost:4318";
var serviceName = Environment.GetEnvironmentVariable("OTEL_SERVICE_NAME")
?? "my-service";
// Setup Traces and Metrics
builder.Services.AddOpenTelemetry()
.ConfigureResource(r => r.AddService(serviceName))
.WithTracing(tracing => tracing
.AddAspNetCoreInstrumentation()
.AddOtlpExporter(opts =>
{
opts.Endpoint = new Uri($"{endpoint}/v1/traces");
opts.Protocol = OtlpExportProtocol.HttpProtobuf;
}))
.WithMetrics(metrics => metrics
.AddAspNetCoreInstrumentation()
.AddOtlpExporter(opts =>
{
opts.Endpoint = new Uri($"{endpoint}/v1/metrics");
opts.Protocol = OtlpExportProtocol.HttpProtobuf;
}));
// Setup Logs
builder.Logging.AddOpenTelemetry(logging =>
{
logging.SetResourceBuilder(ResourceBuilder.CreateDefault().AddService(serviceName));
logging.AddOtlpExporter(opts =>
{
opts.Endpoint = new Uri($"{endpoint}/v1/logs");
opts.Protocol = OtlpExportProtocol.HttpProtobuf;
});
});

Important: Use OtlpExportProtocol.HttpProtobuf and append the signal path (/v1/traces, /v1/logs, /v1/metrics) to the endpoint.

Set the required environment variables and run:

Terminal window
export OTEL_EXPORTER_OTLP_ENDPOINT="https://otlp.kopai.app"
export OTEL_SERVICE_NAME="my-service"
dotnet run
VariableDescription
OTEL_EXPORTER_OTLP_ENDPOINTKopai OTLP endpoint
OTEL_SERVICE_NAMEName shown in Kopai UI

For authentication, add headers to the exporter:

opts.Headers = "Authorization=Bearer YOUR_TOKEN";

For a complete working example:

.NET Example