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

.NET Framework 4.8下ILogger无法将日志写入Application Insights

问题分析与修复方案

核心问题定位

从现象(请求到达Ingestion Endpoint但无响应体,PowerShell调用正常)来看,问题出在应用侧的遥测发送逻辑,而非端点或连接配置。结合你的代码,主要有以下几个关键点需要修正:


1. InMemoryChannel未主动刷新遥测

你使用的InMemoryChannel在开启DeveloperMode后,不会自动发送缓存的遥测数据,必须手动调用Flush()才能触发发送,尤其是在非ASP.NET请求上下文(比如后台任务)或应用生命周期结束时。

修复代码:

// 在AbcExceptionLogger类中新增通道引用
private InMemoryChannel _telemetryChannel;

// 初始化Application Insights部分修改:
var telemetryConfiguration = new TelemetryConfiguration(appInsightsConnectionString);
_telemetryChannel = new InMemoryChannel
{
    DeveloperMode = true
};
telemetryConfiguration.TelemetryChannel = _telemetryChannel;

// 实现IDisposable接口,确保销毁时刷新通道
public void Dispose()
{
    _telemetryChannel?.Flush();
    _telemetryChannel?.Dispose();
    _loggerFactory?.Dispose();
}

生产环境建议替换为ServerTelemetryChannel,它会自动批量发送、处理重试,无需手动刷新。


2. TelemetryConfiguration初始化方式错误

使用TelemetryConfiguration.CreateDefault()会优先读取配置文件中的AI设置,后续手动覆盖ConnectionString可能导致部分默认配置丢失,引发发送异常。

修复代码:

// 直接通过连接字符串初始化配置,替代原CreateDefault()逻辑
var telemetryConfiguration = new TelemetryConfiguration(appInsightsConnectionString);

3. 日志级别检查逻辑缺失

你的IsEnabled方法未实现完整逻辑,若判断规则与_minimumLogLevel不匹配,会导致日志被错误过滤。

修复代码:

public bool IsEnabled(LogLevel logLevel)
{
    return logLevel >= _minimumLogLevel;
}

4. AbcTelemetryInitializer存在空引用风险

当请求无Url(比如后台线程任务)时,访问request.Url会抛出空引用异常,导致整条遥测被丢弃。

修复代码:

public void Initialize(ITelemetry telemetry)
{
    var httpContext = HttpContext.Current;
    if (httpContext != null && httpContext.Request.Url != null) // 新增Url空值检查
    {
        var request = httpContext.Request;
        // 原Url相关属性设置代码保持不变
    }

    // 其余初始化逻辑保持不变
}

5. 显式配置AI日志级别

默认情况下,Application Insights日志提供程序可能过滤低级别日志,需显式配置日志级别规则:

修复代码:

var options = new ApplicationInsightsLoggerOptions
{
    LogLevel =
    {
        Default = _minimumLogLevel, // 与你的全局最低日志级别对齐
    }
};

验证步骤

  • 确认配置文件中LoggerProvider值确实为ApplicationInsights;
  • 添加AI调试日志,查看发送过程中的错误:
    <!-- 写入Web.config/App.config的configuration节点下 -->
    <system.diagnostics>
        <trace autoflush="true" />
        <sources>
            <source name="Microsoft.ApplicationInsights" switchValue="Verbose">
                <listeners>
                    <add name="aiDebugListener" type="Microsoft.ApplicationInsights.DebugTelemetryListener, Microsoft.ApplicationInsights" />
                </listeners>
            </source>
        </sources>
    </system.diagnostics>
    
  • 检查Windows事件查看器中Application Insights相关错误日志。

内容的提问来源于stack exchange,提问作者Wathma Rathnayake

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 11:15:14