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

.NET 8 Isolated Function日志在App Insights中级别显示异常求助

.NET 8 Isolated v4 Azure Function App Insights日志级别异常问题

问题现象

使用.NET 8 Isolated v4版本的Azure Function,配置App Insights后,所有测试日志在事务搜索中均显示为Trace条目,Severity级别始终为"Information",即便调用了LogError、LogInformation等不同级别的日志方法。

测试代码:

_logger.LogTrace("TestLog Trace");
_logger.LogInformation("TestLog Information");
_logger.LogError( "TestLog Error");
_logger.LogError(new Exception("something wrong"),"TestLog ErrorWithException");

配置文件(appsettings.json)

{
  "IsEncrypted": false,
  "Values": {
    SNIPPED
  },
  "logging": {
    "fileLoggingMode": "always",
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": true,
        "excludedTypes": "Request"
      }
    },
    "logLevel": {
      "default": "Trace",
      "xxFunction.DoSomeAction": "Debug",
      "xxFunction.Login": "Debug",
      "xxFunction.WelcomeGiftQueue": "Debug"
    },
    "extensions": {
      "queues": {
        "maxPollingInterval": "00:00:10",
        "visibilityTimeout": "00:00:30",
        "batchSize": 16,
        "maxDequeueCount": 5,
        "newBatchThreshold": 8,
        "messageEncoding": "base64"
      }
    }
  },
  "ApplicationInsights": {
    "LogLevel": {
      "Default": "Trace"
    }
  }
}

Program.cs代码

using Application.Interfaces;
using AzureFunctionApp.Functions.Middleware;
using Infrastructure;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Azure.Core.Serialization;
using Newtonsoft.Json.Converters;

public class Program
{
    static ILogger _logger;

    public Program(ILoggerFactory loggerFactory)
    {
        _logger = loggerFactory.CreateLogger<Program>();
    }

    public static void Main()
    {
        var host = new HostBuilder()
            .ConfigureFunctionsWorkerDefaults(builder =>
            {
                builder.UseMiddleware<ExceptionLoggingMiddleware>();

                builder.UseWhen<AuthenticationMiddleware>(ctx =>
                {
                    return ctx.FunctionDefinition.InputBindings.Values
                                  .First(a => a.Type.EndsWith("Trigger")).Type == "httpTrigger";
                });
            })
            .ConfigureServices((ctx, serviceProvider) =>
            {
                serviceProvider.AddApplicationInsightsTelemetryWorkerService();

                serviceProvider.ConfigureFunctionsApplicationInsights();

                serviceProvider.Configure<WorkerOptions>(workerOptions =>
                {
                    JsonSerializerSettings settings = NewtonsoftJsonObjectSerializer.CreateJsonSerializerSettings();
                    settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                    settings.NullValueHandling = NullValueHandling.Ignore;
                    workerOptions.Serializer = new NewtonsoftJsonObjectSerializer(settings);
                });

                serviceProvider.AddInfrastructureServices(ctx.Configuration);
            })
            .ConfigureAppConfiguration((hostContext, config) =>
            {
                config.AddJsonFile("appsettings.json", optional: true);
            })
            .ConfigureLogging((hostingContext, logging) =>
            {
                logging.ClearProviders();
                logging.AddSimpleConsole(console =>
                {
                    console.IncludeScopes = true;
                });

                logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
            })
            .Build();

        host.Run();
    }
}

解决方案

问题根源在于ConfigureLogging中调用了logging.ClearProviders(),该操作会移除Application Insights的日志提供程序,导致后续日志无法正确识别级别,全部以默认的Information级别发送到App Insights。

修改方案1:移除ClearProviders调用

修改Program.cs中的ConfigureLogging部分,删除logging.ClearProviders():

.ConfigureLogging((hostingContext, logging) =>
{
    logging.AddSimpleConsole(console =>
    {
        console.IncludeScopes = true;
    });

    logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
})

修改方案2:清除后重新添加App Insights提供程序

若确实需要清除其他日志提供程序,手动重新添加Application Insights:

.ConfigureLogging((hostingContext, logging) =>
{
    logging.ClearProviders();
    logging.AddSimpleConsole(console =>
    {
        console.IncludeScopes = true;
    });
    // 重新添加Application Insights日志提供程序
    logging.AddApplicationInsights();
    logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
})

同时确保ConfigureFunctionsApplicationInsights()在AddApplicationInsightsTelemetryWorkerService()之后调用,该方法会配置Azure Function特有的App Insights设置,包括日志级别映射。

修改完成后,不同级别的日志会正确显示对应的Severity级别,Error日志将标记为Error级别,不再统一显示为Information。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 03:49:59