我的问题是:
在我的场景中注入(inject)自定义关联/操作 ID 的正确/更好的方法是什么,该方法不会导致内存泄漏,并且可以正确使用并显示在 Azure 门户上?
以下是我的场景的具体细节:
我有一个 Azure 辅助角色,它不断地从 Azure 队列中取出消息并进行处理。该消息包含关联 ID(操作 ID)和操作名称,我希望将其用于在该消息的处理工作期间通过 Application Insights 收集和推送的所有遥测数据。
当前实现的方式是通过自定义的ITelemetryInitializer
,它看起来像这样:
public class MiTelemetryInitialiser : ITelemetryInitializer
{
private readonly ILoggingContext _context;
public MiTelemetryInitialiser(ILoggingContext context)
{
_context = context;
}
public void Initialize(ITelemetry telemetry)
{
if (string.IsNullOrEmpty(telemetry.Context.Operation.Id) && _context != null)
{
telemetry.Context.Operation.Id = _context.OperationId;
if (!String.IsNullOrWhiteSpace(_context.OperationName))
telemetry.Context.Operation.Name = _context.OperationName;
}
}
}
然后我的工作角色处理循环看起来像这样(si:
while(!cancellationToken.IsCancellationRequested) {
// 1. Get message from the queue
// 2. Extract operation name and Correlation Id from the message
TelemetryConfiguration config = TelemetryConfiguration.CreateDefault();
var loggingContext = //new logging context with operation name and correlation id
config.TelemetryInitializers.Add(new MiTelemetryInitialiser(loggingContext));
TelemetryClient telemetryClient = new TelemetryClient(config);
// do work
client.Flush();
}
我正在使用这个TelemetryChannel
:
<TelemetryChannel Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.ServerTelemetryChannel, Microsoft.AI.ServerTelemetryChannel"/>
有两个问题:
- 内存泄漏(严重) - 我猜测是由于
ServerTelemetryChannel
的实现方式(不幸的是与大多数 .NET SDK 不同 - 该 channel 不是开源的)以及紧密循环所致? - 尽管
client.TrackRequest()
正在推送我的自定义关联 ID(使用 Fiddler 进行验证),但 Application Insights 会在 Azure 门户上覆盖它,并显示其自己的操作 ID,而不是我的操作 ID。请求期间的其他遥测具有我设置的正确OperationId。
这是运行循环约 10 分钟后内存泄漏的照片(一段时间后增长到 1GB+):
最佳答案
对于内存泄漏问题 - 我们找到了根本原因,我们将在下一个版本中修复它。但是,在您的代码示例中,我们建议不要每次都创建新 channel ,而是重用相同的 channel 。它将允许更好的批处理和更少的内存开销:
TelemetryConfiguration config = TelemetryConfiguration.CreateDefault();
var loggingContext = //new logging context with operation name and correlation id
config.TelemetryInitializers.Add(new MiTelemetryInitialiser(loggingContext));
while(!cancellationToken.IsCancellationRequested) {
// 1. Get message from the queue
// 2. Extract operation name and Correlation Id from the message
TelemetryClient telemetryClient = new TelemetryClient(config);
// do work
client.Flush();
}
或者只是使用这个:
while(!cancellationToken.IsCancellationRequested) {
// 1. Get message from the queue
// 2. Extract operation name and Correlation Id from the message
TelemetryClient telemetryClient = new TelemetryClient();
// do work
client.Flush();
}
并将遥测初始值设定项添加到 ApplicationInsigths.config
中:
<Add Type="Namespace.MiTelemetryInitialiser , AssemblyName" />
另请参阅my blog post关于如何将遥测初始值设定项添加到全局单例配置:
Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration.Active.TelemetryInitializers.Add(new MiTelemetryInitialiser());
关于c# - 如何使用自定义 OperationId 而不会导致内存泄漏并且不会被 Application Insights 忽略?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32650200/