Note:
OpenTelemetry is a collection of tools, APIs, and SDKs for monitoring, generating, collecting, and exporting telemetry data (metrics, logs, and traces) to help users analyze the performance and behaviors of the software. For more information about OpenTelemetry, see the OpenTelemetry Official Website. The OpenTelemetry community is active, with rapid technological changes, and widely compatible with mainstream programming languages, components, and frameworks, making its link-tracing capability highly popular for cloud-native microservices and container architectures.
The OpenTelemetry-dotnet solution supports automatic access of common dependency libraries and frameworks of .NET, such as ASPNET, HTTPCLIENT, and MySQLCONNECTOR, to report link information without modifying the code. For other dependency libraries and frameworks that support automatic access, see the list provided by the OpenTelemetry community. This document describes how to access .NET applications by using the OpenTelemetry .NET SDK. Prerequisites
OpenTelemetry .NET supports both automatic and manual access.
Automatic Access
Versions supporting automatic access:
.NET SDK ≥ 6
.NET Framework does not support automatic access currently.
Manual Access
Versions supporting manual access:
.NET ≥ 5.0
.NET Core ≥ 2.0
.NET Framework ≥ 4.6.1
Demo Application
The example code Program.cs
demonstrates how to access WebApplication to a MySQL database by using MySQLConnector. You can create the corresponding MySQL database or purchase one directly.
1. Initialize the application.
2. Introduce the dependency packages used in the Demo.
Microsoft.Extensions.Logging.Abstractions
is a necessary package for MySqlConnector
.
dotnet add package MySqlConnector;
dotnet add package Microsoft.Extensions.Logging.Abstractions;
3. Modify the content of the Properties/launchSettings.json
file.
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:8080",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
4. Write the business code in Program.cs
.
Program.cs
demonstrates how to call the WebApplication API to simulate access to a MySQL database by using MySQLConnector.
using MySqlConnector;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.MapGet("/todo", () =>
{
string connectionString = "server=localhost;port=3306;User Id=root;password=;Database=MyDB";
using (MySqlConnection myConnnect = new MySqlConnection(connectionString))
{
try
{
myConnnect.Open();
using (MySqlCommand myCmd = new MySqlCommand("select * from MyTable", myConnnect))
{
using (MySqlDataReader reader = myCmd.ExecuteReader())
{
List<Int32> results = new List<Int32>();
while (reader.Read())
{
results.Add(reader.GetInt32(0));
}
return "ids:" + string.Join(", ", results);
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Database operation error: {ex.Message}");
return "Database operation error";
}
}
});
app.Run();
Previous Steps: Get the Access Point and Token
1. Log in to the TCOP console. 2. In the left sidebar, select Application Performance Management > Application list, click Access application.
3. In the right sidebar Data access drawer, click .NET language.
4. On the Access .NET application page, select the Region and Business System you want to integrate.
5. Select Access protocol type as OpenTelemetry.
6. Reporting method Choose your desired reporting method, and obtain your Access Point and Token.
Note:
Report over private network: Using this reporting method, your service needs to run in the Tencent Cloud VPC. Through VPC connecting directly, you can avoid the security risks of public network communication and save on reporting traffic overhead.
Report over public network: If your service is deployed locally or in non-Tencent Cloud VPC, you can report data in this method. However, it involves security risks in public network communication and incurs reporting traffic fees.
Automatic Access Scheme (Recommended)
Step 1: Install opentelemetry-dotnet-instrumentation
1. Download and execute the script for installing OpenTelemetry .NET instrumentation.
curl -L -O https://github.com/open-telemetry/opentelemetry-dotnet-instrumentation/releases/latest/download/otel-dotnet-auto-install.sh
chmod -x otel-dotnet-auto-install.sh
sh ./otel-dotnet-auto-install.sh
2. Set the environment variables and execute the OpenTelemetry .NET instrumentation script.
chmod -x $HOME/.otel-dotnet-auto/instrument.sh
export OTEL_TRACES_EXPORTER=otlp \\
OTEL_METRICS_EXPORTER=none \\
OTEL_LOGS_EXPORTER=none \\
OTEL_SERVICE_NAME=<service-name> \\
OTEL_EXPORTER_OTLP_PROTOCOL=grpc \\
OTEL_EXPORTER_OTLP_ENDPOINT=<endpoint> \\
OTEL_RESOURCE_ATTRIBUTES="token=<token>"
. $HOME/.otel-dotnet-auto/instrument.sh
Note:
If you install opentelemetry-dotnet-instrumentation on macOS systems, the coreutils tool is required. Step 2: Run the Application
1. Build and run the application.
2. Visit the following link in the browser:
http://localhost:8080
http://localhost:8080/todo
Each time you visit this page, OpenTelemetry will automatically create a Trace and report the linkage data to APM.
Access Verification
After launching the .NET application, access the corresponding interface through port 8080, for example, https://localhost:8080/todo
. In case of normal traffic, the connected application will be displayed in APM > Application list. Click on the Application Name/ID to enter the application details page, then select Instance monitoring to view the connected application instance. Due to some delay in processing observable data, if the application or instance is not found in the console after connecting, please wait about 30 seconds. Custom Event Tracking (Optional)
When automatic event tracking does not meet your scenarios, or you need to add business layer event tracking, you can refer to the following content and use opentelemetry-dotnet-instrumentation to add custom event tracking. This document only demonstrates the most basic custom event tracking method. The OpenTelemetry community provides more flexible custom event tracking methods. For specific methods, see the document Custom instrumentation for .NET provided by the OpenTelemetry community. Introduce the Dependency Package System.Diagnostics.DiagnosticSource
dotnet add package System.Diagnostics.DiagnosticSource
Create an ActivitySource Instance
private static readonly ActivitySource RegisteredActivity = new ActivitySource("Examples.ManualInstrumentations.Registered");
Create an Activity
using (var activity = RegisteredActivity.StartActivity("Main"))
{
activity?.SetTag("key", "3.1415");
activity?.AddEvent(new("something happened"));
Thread.Sleep(1000);
}
Register an ActivitySource in OpenTelemetry.AutoInstrumentation
Set the environment variable OTEL_DOTNET_AUTO_TRACES_ADDITIONAL_SOURCES
. ActivitySources not registered in this way will not be reported.
export
OTEL_DOTNET_AUTO_TRACES_ADDITIONAL_SOURCES=Examples.ManualInstrumentations.Registered
Manual Access Scheme
If the .NET SDK version is not later than 6 or .NET Framework is used, but the manual access conditions are met, you can choose manual access for reporting. This document only demonstrates the most basic manual event tracking method. The OpenTelemetry community provides more flexible manual event tracking methods. For specific methods, see the document Instrumentation for .NET provided by the OpenTelemetry community. Step 1: Install OpenTelemetry Dependencies Required for Manual Access
1. Install the OpenTelemetry dependencies required for manual access.
dotnet add package OpenTelemetry
dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol
dotnet add package OpenTelemetry.Extensions.Hosting
dotnet add package OpenTelemetry.Instrumentation.AspNetCore
Step 2: Initialize the OpenTelemetry SDK
1. Create a tracerProvider
and add the following code at the beginning of your program.
var serviceName = "<service-name>";
using var tracerProvider = Sdk.CreateTracerProviderBuilder()
.AddSource(serviceName)
.SetResourceBuilder(
ResourceBuilder.CreateDefault().AddService(serviceName)
.AddAttributes(new Dictionary<string, object>
{
["token"] = "<token>",
["host.name"] = "<host>"
}))
.AddOtlpExporter(opt =>
{
opt.Endpoint = new Uri("<endpoint>");
opt.Protocol = OtlpExportProtocol.Grpc;
})
.Build();
Step 3: Modify the Application Code and Use ActivitySource to Create an Activity
1. Create an ActivitySource
for creating an Activity
at any place in the application that requires manual access.
The ActivitySource is equivalent to a Tracer of OpenTelemetry.
var MyActivitySource = new ActivitySource(serviceName);
2. After the ActivitySource
is created, create an Activity
.
The Activity is equivalent to a Span of OpenTelemetry.
using var activity = MyActivitySource.StartActivity("SayHello");
activity?.SetTag("key", "3.1415");
activity?.AddEvent(new("something happened"));
Step 4: Run the Program
Build and run the application.
Access Verification
Run the .NET application. In case of normal traffic, the connected application will be displayed in APM > Application list. Click on the Application Name/ID to enter the application details page, then select Instance monitoring to view the connected application instance. Due to some delay in processing observable data, if the application or instance is not found in the console after connecting, please wait about 30 seconds.
Was this page helpful?