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

Azure中如何在.NET 5.0的ASP.NET Core应用中编写并读取自定义日志消息(含Pulumi部署场景)

解决ASP.NET Core部署到Azure后的自定义日志查看问题

你遇到的核心问题之一其实是日志级别不匹配——你的代码输出的是LogInformation,但Pulumi里配置的FileSystemLevel是Error,所以信息级别的日志根本不会被Azure App Service捕获!先从这个关键点入手,逐个解决你的问题:

1. 代码层面的配置

其实你现有的代码已经基本没问题了,再确认几个细节:

  • NuGet包:.NET 5的ASP.NET Core项目默认已经包含Microsoft.Extensions.Logging和Microsoft.Extensions.Logging.Abstractions,不需要额外安装。如果后续要接入Application Insights,需要安装Microsoft.ApplicationInsights.AspNetCore包。
  • Program/Startup配置:用Host.CreateDefaultBuilder(.NET 5默认模板就是这个)已经自动配置了控制台、调试输出等日志提供器。可以在appsettings.json里调整全局日志级别,确保自定义信息日志能正常输出:
    {
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft": "Warning",
          "Microsoft.Hosting.Lifetime": "Information"
        }
      }
    }
    
  • 日志代码:你控制器里的_logger.LogInformation("Hello, World!");写法完全正确,不需要修改。

2. Azure端的配置(通过Pulumi调整)

你的Pulumi代码里的日志配置需要调整,才能捕获信息级别的日志:

  • 修改ApplicationLogs.FileSystemLevel为Information或者Verbose(如果需要更详细的日志):
    var app = new AppService( 
        "kmsApp", 
        new AppServiceArgs { 
            Logs = new AppServiceLogsArgs { 
                ApplicationLogs = new AppServiceLogsApplicationLogsArgs { 
                    FileSystemLevel = "Information" // 从Error改为Information
                }, 
                DetailedErrorMessagesEnabled = true, 
                FailedRequestTracingEnabled = true, 
                HttpLogs = new AppServiceLogsHttpLogsArgs { 
                    FileSystem = new AppServiceLogsHttpLogsFileSystemArgs { 
                        RetentionInDays = 1, 
                        RetentionInMb = 35 
                    } 
                } 
            } 
        }, 
        ...);
    
  • (可选但推荐)接入Application Insights:如果想更方便地查询和分析日志,建议在Pulumi里创建一个Application Insights资源并关联到你的App Service:
    var insights = new ApplicationInsights("kmsAppInsights", new ApplicationInsightsArgs
    {
        ResourceGroupName = resourceGroup.Name,
        ApplicationType = "web"
    });
    
    // 在AppService配置中添加关联设置
    var app = new AppService("kmsApp", new AppServiceArgs
    {
        // 其他已有配置...
        AppSettings = 
        {
            { "APPINSIGHTS_INSTRUMENTATIONKEY", insights.InstrumentationKey },
            { "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES", "Microsoft.ApplicationInsights.AspNetCore" }
        }
    });
    
    这样日志会自动同步到Application Insights,查询和筛选会更灵活。

3. 在Azure浏览器GUI中查看日志

有几个常用的入口,按便捷度排序:

  • 日志流(Log Stream):
    1. 打开Azure Portal,找到你的App Service资源
    2. 在左侧菜单的「监视」分类下,点击「日志流」
    3. 选择「应用程序日志文件系统」,就能实时看到你的LogInformation日志输出
  • Kudu高级工具:
    1. 在App Service左侧菜单,点击「开发工具」下的「高级工具」,点击「Go」进入Kudu界面
    2. 点击「Debug console」→「CMD」,导航到LogFiles/Application目录
    3. 目录里的*.txt文件就是你的应用日志,直接打开即可查看历史日志
  • Application Insights(如果配置了):
    1. 打开对应的Application Insights资源
    2. 左侧菜单点击「日志」(Logs)
    3. 在查询编辑器中输入traces | where message contains "Hello, World!",点击运行就能精准定位到你的自定义日志

4. 编程方式获取日志

方式1:通过Azure Management API读取App Service文件系统日志

使用Microsoft.Azure.Management.WebSites NuGet包,借助Azure认证(比如服务主体)调用API获取日志:

using Microsoft.Azure.Management.WebSites;
using Microsoft.Rest;

// 初始化客户端(需提前获取Azure访问令牌)
var credentials = new TokenCredentials("your-access-token");
var webSiteClient = new WebSiteManagementClient(credentials) { SubscriptionId = "your-subscription-id" };

// 获取日志文件列表或直接下载内容
var logFiles = await webSiteClient.WebApps.ListApplicationLogsAsync("your-resource-group", "kmsApp");
var logContentStream = await webSiteClient.WebApps.DownloadApplicationLogsAsync("your-resource-group", "kmsApp");

方式2:通过Application Insights API查询日志

如果配置了Application Insights,可使用Microsoft.Azure.ApplicationInsights.Query NuGet包执行日志查询:

using Microsoft.Azure.ApplicationInsights.Query;
using Microsoft.Rest;

var credentials = new TokenCredentials("your-access-token");
var queryClient = new ApplicationInsightsDataClient(credentials);

// 执行自定义查询
var results = await queryClient.Query.ExecuteAsync(
    "your-app-insights-app-id", 
    "traces | where message contains 'Hello, World!' | order by timestamp desc"
);

方式3:Pulumi中间接获取日志

Pulumi本身不直接提供日志读取能力,但你可以在Pulumi代码中调用上述Azure API,或者配置日志存储到Azure Blob Storage(在Pulumi的HttpLogs里添加Blob配置),再通过Blob SDK读取日志文件。

推荐的核心文档

  • Azure App Service应用日志配置文档:重点关注日志级别设置和日志存储选项
  • ASP.NET Core日志官方文档:明确.NET 5日志的默认行为和扩展方式
  • Application Insights日志查询指南:如果使用AI,这是自定义日志查询的核心参考

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 11:23:23