我何时可以获得应用程序洞察操作id
本文关键字:洞察 操作 id 应用程序 何时可 | 更新日期: 2023-09-27 18:04:12
我有一个AspNetCore web应用程序,写入EventHub和一个从它读取的webjob。我希望此事务的两个部分的遥测在Application Insights中具有相同的操作id。
因此,当我要将数据发送到EventHub时,我尝试将操作id从TelemetryClient中拉出来,例如
var myOperationId = MyTelemetryClient.Context.Operation.Id;
但这总是给我null。我找到了这篇文章,并尝试使用
var request.HttpContext.Items["Microsoft.ApplicationInsights.RequestTelemetry"] as RequestTelemetry;
但还是null。当我需要这个值时,有什么方法可以提取它的指针吗?
我的代码是这样的:
public class Startup
{
public void ConfigureServices( IServiceCollection IServices )
{
var builder = TelemetryConfiguration.Active.TelemetryProcessorChainBuilder;
builder.Use((next) => new MyTelemetryProcessor(next));
builder.Build();
var aiOptions = new Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions();
aiOptions.EnableQuickPulseMetricStream = true;
IServices.AddApplicationInsightsTelemetry( Configuration, aiOptions);
IServices.AddMvc();
IServices.AddOptions();
TelemetryClient AppTelemetry = new TelemetryClient();
AppTelemetry.InstrumentationKey = InsightsInstrumentationKey;
IServices.AddSingleton(typeof(TelemetryClient), AppTelemetry);
}
public void Configure( IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory )
{
app.UseApplicationInsightsRequestTelemetry();
app.UseApplicationInsightsExceptionTelemetry();
app.UseMvc();
var configuration = app.ApplicationServices.GetService<TelemetryConfiguration>();
configuration.TelemetryInitializers.Add(new MyTelemetryInitializer());
}
}
[Route("[controller]")]
public class MyController
{
private readonly TelemetryClient mTelemetryClient;
public MyController(
TelemetryClient TelemetryClientArg)
{
mTelemetryClient = TelemetryClientArg;
}
[HttpPost]
public async Task<IActionResult> Post([FromBody]MyPostDataClass MyPostData)
{
string telemetryId = mTelemetryClient.Context.Operation.Id; // this is null
return Ok();
}
}
我的TelemetryConfiguration .Active.TelemetryInitializers
中没有OperationIdTelemetryInitializer
但是这为我提供了当前操作id:
System.Diagnostics.Activity.Current.RootId
https://github.com/Microsoft/ApplicationInsights-aspnetcore/issues/504 我想我终于在没有创建不必要的遥测的情况下破解了它。以下是针对AspNetCore的,但只要操作id初始化器可用,就应该转换:
var operationId = default(string);
try
{
var telemetry = new RequestTelemetry();
TelemetryConfiguration
.Active
.TelemetryInitializers
.OfType<OperationIdTelemetryInitializer>()
.Single()
.Initialize(telemetry);
operationId = telemetry.Context.Operation.Id;
}
catch { }
Net核心包有一个OperationIdTelemetryInitializer
(见github),它试图从请求设置这个。假设如果你有请求跟踪并且开启了这个遥测初始化器,那么在那个请求中发生的所有事情都应该有一个Operation。Id集合。
如果这对你不起作用,你可以创建自己的自定义TelemetryInitializer
来设置它,但是你需要,或者,在你发现它为空的地方,你可以把它设置在那里,所有的东西在那个上下文应该有那个id。
您可以通过发送一段遥测数据,然后从遥测对象中读取操作id来获取此值。不是很优雅,但是很好用。
[HttpPost]
public async Task<IActionResult> Post([FromBody]MyPostDataClass MyPostData)
{
var dummyTrace = new TraceTelemetry("hello", SeverityLevel.Verbose);
mTelemetryClient.TrackTrace(dummyTrace);
string opId = dummyTrace.Context.Operation.Id;
return Ok();
}