You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 6 ASP.NET应用Application Insights遥测丢失报错求助

问题:.NET 6 ASP.NET应用向Application Insights日志报错:"AI: Process was called on the TelemetrySink after it was disposed, the telemetry data was dropped."

应用环境与错误详情

  • NuGet包版本:
    • Microsoft.ApplicationInsights.AspNetCore 2.21.0
    • Microsoft.ApplicationInsights.Profiler.AspNetCore 2.4.0
  • 错误跟踪核心属性:
    • 日志级别:Verbose
    • 遥测类型:trace
    • 操作名称:POST Purchase/PurchaseTransaction
    • 运行环境:Production
    • SDK版本:dotnetc:2.21.0-429

现有配置与代码

Startup类配置

public void ConfigureServices(IServiceCollection services)
{
    services.AddApplicationInsightsTelemetry();
    services.AddServiceProfiler();
}

控制器日志代码

[ApiController]
[Route("/api/purchase")]
public class PurchaseController
{
    private readonly ILogger<PurchaseController> _logger;

    public PurchaseController(ILogger<PurchaseController> logger)
    {
        _logger = logger;
    }

    [HttpPost("purchase-transaction")]
    [ProducesResponseType(StatusCodes.Status201Created)]
    [ProducesResponseType(StatusCodes.Status403Forbidden)]
    public async Task<IActionResult> PurchaseTransaction([FromBody] GlassfyRequestDto dto)
    {
        string jsonString = JsonSerializer.Serialize(dto);
        _logger.LogInformation(jsonString);     
        _logger.LogError("PurchaseTransactionData", dto);
        
        return Ok(jsonString);
    }
}

GlassfyRequestDto类

using Newtonsoft.Json;

namespace WebApi.Controllers.Dto
{
    public class GlassfyRequestDto
    {
        [JsonProperty("app_version")]
        public string AppVersion { get; set; }

        [JsonProperty("appid")]
        public string Appid { get; set; }

        [JsonProperty("appsFlyerId")]
        public string AppsFlyerId { get; set; }

        [JsonProperty("auto_renew_product_id")]
        public string AutoRenewProductId { get; set; }

        [JsonProperty("auto_renew_status")]
        public bool AutoRenewStatus { get; set; }

        [JsonProperty("bundle_version")]
        public string BundleVersion { get; set; }

        [JsonProperty("country_code")]
        public string CountryCode { get; set; }

        [JsonProperty("currency_code")]
        public string CurrencyCode { get; set; }

        [JsonProperty("customid")]
        public string Customid { get; set; }

        [JsonProperty("date_ms")]
        public long DateMs { get; set; }

        [JsonProperty("days")]
        public int Days { get; set; }

        [JsonProperty("device")]
        public string Device { get; set; }

        [JsonProperty("duration")]
        public int Duration { get; set; }

        [JsonProperty("environment")]
        public string Environment { get; set; }

        [JsonProperty("estimated")]
        public int Estimated { get; set; }

        [JsonProperty("event_date")]
        public int EventDate { get; set; }

        [JsonProperty("expiration_intent")]
        public string ExpirationIntent { get; set; }

        [JsonProperty("expire_date_ms")]
        public long ExpireDateMs { get; set; }

        [JsonProperty("grace_period_expires_date_ms")]
        public int GracePeriodExpiresDateMs { get; set; }

        [JsonProperty("id")]
        public string Id { get; set; }

        [JsonProperty("is_in_billing_retry_period")]
        public bool IsInBillingRetryPeriod { get; set; }

        [JsonProperty("months")]
        public int Months { get; set; }

        [JsonProperty("offer_code_ref_name")]
        public string OfferCodeRefName { get; set; }

        [JsonProperty("offeringid")]
        public string Offeringid { get; set; }

        [JsonProperty("original_purchase_date_ms")]
        public long OriginalPurchaseDateMs { get; set; }

        [JsonProperty("original_transaction_id")]
        public string OriginalTransactionId { get; set; }

        [JsonProperty("price")]
        public double Price { get; set; }

        [JsonProperty("price_consent_status")]
        public string PriceConsentStatus { get; set; }

        [JsonProperty("price_usd")]
        public double PriceUsd { get; set; }

        [JsonProperty("productid")]
        public string Productid { get; set; }

        [JsonProperty("sdk_version")]
        public string SdkVersion { get; set; }

        [JsonProperty("sort_date_ms")]
        public long SortDateMs { get; set; }

        [JsonProperty("source")]
        public string Source { get; set; }

        [JsonProperty("store")]
        public string Store { get; set; }

        [JsonProperty("sub_platform")]
        public string SubPlatform { get; set; }

        [JsonProperty("subscriberid")]
        public string Subscriberid { get; set; }

        [JsonProperty("system_version")]
        public string SystemVersion { get; set; }

        [JsonProperty("type")]
        public int Type { get; set; }

        [JsonProperty("userunknown")]
        public bool Userunknown { get; set; }

        [JsonProperty("vendorid")]
        public string Vendorid { get; set; }

        [JsonProperty("web_order_line_item_id")]
        public string WebOrderLineItemId { get; set; }

        [JsonProperty("weeks")]
        public int Weeks { get; set; }
    }
}

排查与解决方案

1. 升级Application Insights SDK版本

你使用的Microsoft.ApplicationInsights.AspNetCore 2.21.0存在已知的TelemetrySink释放后调用的bug,后续版本已修复。建议升级到2.22.0及以上版本,优先选择最新稳定版。

2. 修正日志调用方式

当前代码中_logger.LogError("PurchaseTransactionData", dto)的调用不符合日志API规范:LogError的第二个参数应为异常对象,而非自定义数据。错误的参数传递可能触发内部序列化异常,间接导致资源释放问题。改为结构化日志写法:

// 结构化日志,便于在Application Insights中查询分析
_logger.LogError("PurchaseTransactionData: {TransactionData}", jsonString);

3. 同步升级Service Profiler包

Microsoft.ApplicationInsights.Profiler.AspNetCore需与Application Insights SDK版本兼容,升级SDK后建议同步升级Profiler包到匹配版本,避免版本冲突引发的资源生命周期异常。

4. 确保日志操作在请求生命周期内完成

检查是否存在请求返回后(如Ok(jsonString)之后)触发的延迟日志逻辑(比如后台任务、异步回调),这类操作会在TelemetrySink已被释放时执行,导致报错。所有日志操作应确保在请求处理流程内完成。

5. 显式配置TelemetrySink生命周期(可选)

若升级后问题仍存在,可显式将TelemetrySink注册为单例,避免提前释放:

services.AddApplicationInsightsTelemetry();
services.AddSingleton<ITelemetrySink>(sp => sp.GetRequiredService<TelemetrySink>());
services.AddServiceProfiler();

内容的提问来源于stack exchange,提问作者Ivo Oostwegel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 15:40:38