前提条件
完成vpce接入。
背景信息
OpenTelemetry c# SDK提供了c#语言的分布式链路追踪能力,您可以直接使用OTLP gRPC或者HTTP协议向APM服务端上报数据。
接入步骤
1、安装依赖包
dotnet add package OpenTelemetry.Exporter.Console
dotnet add package OpenTelemetry.Extensions.Hosting
dotnet add package OpenTelemetry.Instrumentation.AspNetCore
dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol
2、查看接入点信息
应用列表的接入指引会根据您所在资源池提供“通过 HTTP 上报数据”和“通过 gRPC 上报数据”的ENDPOINT(天翼云vpc网络接入点)、鉴权TOKEN信息。
3、初始化SDK并设置exporters
1)使用http协议上报,修改Program.cs代码如下
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;
using OpenTelemetry.Exporter;
// Ideally, you will want this name to come from a config file, constants file, etc.
var serviceName = "csharp-otel-simple-http";
var serviceVersion = "1.0.0";
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenTelemetry()
.ConfigureResource(resource => resource.AddService(
serviceName: serviceName,
serviceVersion: serviceVersion))
.WithTracing(tracing => tracing
.AddSource(serviceName)
.AddAspNetCoreInstrumentation()
.AddConsoleExporter() //在控制台导出Trace数据,可选
.AddOtlpExporter(options =>
{
//使用HTTP协议上报
options.Endpoint = new Uri("<http_endpoint>");
options.Headers = "x-ctg-authorization=<token>";
options.Protocol = OtlpExportProtocol.HttpProtobuf;
}));
builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.Run();
2)使用grpc协议上报,修改Program.cs代码如下
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;
using OpenTelemetry.Exporter;
// Ideally, you will want this name to come from a config file, constants file, etc.
var serviceName = "csharp-otel-simple-grpc";
var serviceVersion = "1.0.0";
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenTelemetry()
.ConfigureResource(resource => resource.AddService(
serviceName: serviceName,
serviceVersion: serviceVersion))
.WithTracing(tracing => tracing
.AddSource(serviceName)
.AddAspNetCoreInstrumentation()
.AddConsoleExporter() //在控制台导出Trace数据,可选
.AddOtlpExporter(options =>
{
//使用gRPC协议上报
options.Endpoint = new Uri("<grpc_endpoint>");
options.Headers = "x-ctg-authorization=<token>";
options.Protocol = OtlpExportProtocol.Grpc;
}));
builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.Run();