若出现重复的操作数据,则会导致应用程序出现混淆和错误。下面是一些可能导致 Application Insights 收集重复操作的原因:
1.应用程序代码中的逻辑有误,导致出现重复的操作数据。 2.在运行 Application Insights 后,数据多次发送到了同一个 Application Insights 实例。 3.同一时间内,有多个应用程序将数据发往 Application Insights,而数据的标识(例如 operation id)却是相同的。
为了解决此问题,可以在 Application Insights 中使用自定义变量来标识每个操作并确保每个操作都只被收集一次。示例代码如下:
C#
var operationId = Guid.NewGuid().ToString();
var telemetry = new Microsoft.ApplicationInsights.DataContracts.RequestTelemetry { Name = "Operation Name", Timestamp = DateTimeOffset.UtcNow, Duration = TimeSpan.FromSeconds(3), ResponseCode = "200", Success = true };
telemetry.Context.Operation.Id = operationId; telemetry.Context.Operation.Name = "One Time Operation"; telemetry.Properties.Add("operationId", operationId); telemetry.TrackRequest();
以上代码将为每个操作生成唯一的操作 ID,将其分配给操作、将其添加到每个跟踪项中,以确保每次操作都只被收集一次。