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

.NET C# Azure Functions中如何排除EntityFramework日志记录?

如何在Azure Functions中排除EntityFramework日志并保留自定义Info日志

要实现排除EntityFramework的日志消息,同时保留你自己的LogInfo()记录,你可以通过日志过滤规则精准控制日志输出。以下是修改后的Program.cs配置:

var config = new ConfigurationBuilder()
    .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
    .AddEnvironmentVariables()
    .Build();
var connectionString = config["defaultConnection"];

// 定义要排除的日志类别前缀
var excludedEfCategories = new[] { "Microsoft.EntityFrameworkCore" };

var host = new HostBuilder()
    .ConfigureFunctionsWorkerDefaults(worker => worker.UseNewtonsoftJson())
    .ConfigureServices(services =>
    {
        services.AddApplicationInsightsTelemetryWorkerService();
        services.ConfigureFunctionsApplicationInsights();
    })
    .ConfigureLogging(logging =>
    {
        logging.Services.Configure<LoggerFilterOptions>(options =>
        {
            // 移除原有Application Insights默认规则(用于自定义规则)
            var defaultAiRule = options.Rules.FirstOrDefault(r => 
                r.ProviderName == "Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider");
            if (defaultAiRule != null)
            {
                options.Rules.Remove(defaultAiRule);
            }

            // 添加自定义规则:允许所有非EF类别的Info及以上级别日志进入AI
            options.Rules.Add(new LoggerFilterRule(
                providerName: "Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider",
                categoryName: null,
                logLevel: LogLevel.Information,
                filter: (category, level) => 
                    level >= LogLevel.Information && 
                    !excludedEfCategories.Any(cat => category.StartsWith(cat))
            ));
        });
    })
    .ConfigureOpenApi()
    .ConfigureServices(services =>
    {
        services.AddDbContext<DijestContext>(options =>
                options.UseSqlServer(
                connectionString,
                sqlServerOptions => sqlServerOptions.CommandTimeout(600)));
    })
    .Build();

host.Run();

关键配置说明:

  • 排除EF日志:通过excludedEfCategories定义要过滤的类别前缀(Microsoft.EntityFrameworkCore是EF所有日志的根类别),在过滤逻辑中排除所有以该前缀开头的日志类别。
  • 保留自定义Info日志:过滤规则中设置level >= LogLevel.Information,确保你的LogInfo()及更高级别的日志(如Warn、Error)能正常发送到Application Insights。
  • 精准控制AI日志提供器:针对Application Insights的日志提供器单独设置规则,不影响其他日志输出(比如控制台日志)。

另外,你也可以通过local.settings.json的Logging配置来实现相同效果,这种方式更灵活无需修改代码:

{
  "Logging": {
    "ApplicationInsights": {
      "LogLevel": {
        "Default": "Information",
        "Microsoft.EntityFrameworkCore": "None"
      }
    }
  }
}

这种配置会直接将EF类别的日志级别设为None,从而完全排除,同时保留默认的Info级别日志。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 12:56:01