【发布时间】:2019-04-09 18:54:39
【问题描述】:
我有一个非常基本的 http-POST 触发 api,它创建了 TelemetryClient。我需要在这个遥测中为每个单独的请求提供一个自定义属性,所以我实现了一个TelemtryProcessor。
但是,当处理后续 POST 请求并创建一个似乎会干扰第一个请求的新 TelemetryClient 时。我最终在 App Insights 中看到大约十几个包含第一个 customPropertyId 的条目,第二个接近 500 个,而实际上这个数字应该平均分配。似乎第二个 TelemetryClient 的创建以某种方式干扰了第一个。
基本代码如下,如果有人对为什么会发生这种情况有任何见解(不是双关语),我将不胜感激。
处理 POST 请求的 ApiController:
public class TestApiController : ApiController
{
public HttpResponseMessage Post([FromBody]RequestInput request)
{
try
{
Task.Run(() => ProcessRequest(request));
return Request.CreateResponse(HttpStatusCode.OK);
}
catch (Exception)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, Constants.GenericErrorMessage);
}
}
private async void ProcessRequest(RequestInput request)
{
string customPropertyId = request.customPropertyId;
//trace handler creates the TelemetryClient for custom property
CustomTelemetryProcessor handler = new CustomTelemetryProcessor(customPropertyId);
//etc.....
}
}
创建 TelemetryClient 的 CustomTelemetryProcessor:
public class CustomTelemetryProcessor
{
private readonly string _customPropertyId;
private readonly TelemetryClient _telemetryClient;
public CustomTelemetryProcessor(string customPropertyId)
{
_customPropertyId = customPropertyId;
var builder = TelemetryConfiguration.Active.TelemetryProcessorChainBuilder;
builder.Use((next) => new TelemetryProcessor(next, _customPropertyId));
builder.Build();
_telemetryClient = new TelemetryClient();
}
}
遥测处理器:
public class TelemetryProcessor : ITelemetryProcessor
{
private string CustomPropertyId { get; }
private ITelemetryProcessor Next { get; set; }
// Link processors to each other in a chain.
public TelemetryProcessor(ITelemetryProcessor next, string customPropertyId)
{
CustomPropertyId = customPropertyId;
Next = next;
}
public void Process(ITelemetry item)
{
if (!item.Context.Properties.ContainsKey("CustomPropertyId"))
{
item.Context.Properties.Add("CustomPropertyId", CustomPropertyId);
}
else
{
item.Context.Properties["CustomPropertyId"] = CustomPropertyId;
}
Next.Process(item);
}
}
【问题讨论】:
标签: azure-application-insights