我正在实现一个能够在外部服务中注册遥测的 SDK,并且因为我希望它是供应商中立的,所以我使用 OpenTelemetry。我正在使用的导出器之一是 Azure Monitor 导出器,用于将遥测数据发送到 Application Insight,但来自 OpenTelemetry 的所有遥测数据(跨度、指标、日志)都被注册为跟踪类型或依赖项类型,我希望能够将遥测数据注册为自定义事件(来自 Application Insights)。 我看到了这个 Python 扩展,但无法找到类似的 .Net 解决方案https://github.com/Azure/azure-sdk-for-python/issues/33472
我已经尝试使用 OpenTelemetry 提供的所有工具(跨度、活动、指标和日志)。
如何使用 OpenTelemetry .NET 在 Application Insights 中注册自定义事件
使用下面的代码,我可以通过使用 C# 中的开放遥测来注册自定义事件。
代码:
using System;
using Microsoft.Extensions.Logging;
using OpenTelemetry;
using OpenTelemetry.Trace;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.DataContracts;
using OpenTelemetry.Resources;
using Azure.Monitor.OpenTelemetry.Exporter;
class Program
{
[Obsolete]
static void Main(string[] args)
{
// Initialize OpenTelemetry with Azure Monitor exporter
using var tracerProvider = Sdk.CreateTracerProviderBuilder()
.AddSource("YourApplication")
.SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("sample"))
.AddAzureMonitorTraceExporter(options =>
{
options.ConnectionString = "your-azure-monitor conn-string";
})
.Build();
// Create a custom event
var customEvent = new MyCustomEvent
{
Name = "CustomEvent",
Property1 = "Value1",
Property2 = "Value2"
};
// Send the custom event to Application Insights
SendCustomEventToApplicationInsights(customEvent);
}
[Obsolete]
static void SendCustomEventToApplicationInsights(MyCustomEvent customEvent)
{
// Initialize Application Insights TelemetryClient
var telemetryClient = new TelemetryClient
{
InstrumentationKey = "your-application insights instrumentation-key"
};
// Track the custom event using TelemetryClient
var properties = new Dictionary<string, string>
{
{ "Property1", customEvent.Property1 },
{ "Property2", customEvent.Property2 }
};
telemetryClient.TrackEvent(customEvent.Name, properties);
telemetryClient.Flush(); // Flush the telemetry to ensure it is sent immediately
}
}
class MyCustomEvent
{
public string? Name { get; set; }
public string? Property1 { get; set; }
public string? Property2 { get; set; }
}
我能够在应用程序洞察中看到自定义事件。检查下面:
输出: