我需要如何登录才能在 App Service 日志中查看我的日志

How do I need to log to see my logs in App Service logs

我已启用日志记录到应用程序日志记录到文件系统和 Blob。我使用 ILogger<T>.LogInformation()Trace.WriteLine() 记录消息。 None 其中在 blob 中可见。我也无法在文件系统上找到它们。当我启用日志流时,我也看不到它们。

我是否需要在我的 ASP.NET 核心应用程序中配置一些东西?

[Microsoft.Extensions.Logging.AzureAppServices][1] 提供程序包将日志写入 Azure 应用服务应用程序文件系统中的文本文件以及 Azure 存储帐户中的 blob 存储。

提供程序包未包含在共享框架中。要使用提供程序,请将提供程序包添加到项目中。

要配置提供商设置,请使用 AzureFileLoggerOptions and AzureBlobLoggerOptions,如下例所示:

public static void Main(string[] args)
{
    var host = CreateHostBuilder(args).Build();

    var todoRepository = host.Services.GetRequiredService<ITodoRepository>();
    todoRepository.Add(new Core.Model.TodoItem() { Name = "Feed the dog" });
    todoRepository.Add(new Core.Model.TodoItem() { Name = "Walk the dog" });

    var logger = host.Services.GetRequiredService<ILogger<Program>>();
    logger.LogInformation("Seeded the database.");

    host.Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureLogging(logging => logging.AddAzureWebAppDiagnostics())
            .ConfigureServices(serviceCollection => serviceCollection
                .Configure<AzureFileLoggerOptions>(options =>
                {
                    options.FileName = "azure-diagnostics-";
                    options.FileSizeLimit = 50 * 1024;
                    options.RetainedFileCountLimit = 5;
                }).Configure<AzureBlobLoggerOptions>(options =>
                {
                    options.BlobName = "log.txt";
                })
            )
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

您可以参考下方 link 以获取更多参考:

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-3.1#azure-app-service-provider

希望对您有所帮助。

这里有一个简单的方法(参考文章here):

我用 .NET core 2.2 mvc 项目测试过它。

必要的nuget包:

Microsoft.Extensions.Logging.AzureAppServices, version 2.2.0

1.In Startup.cs -> ConfigureServices方法,添加这行代码:

services.AddSingleton<ILoggerFactory>(new LoggerFactory());

Startup.cs -> Configure方法中,修改如下:

       public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            //add the following code here
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            loggerFactory.AddAzureWebAppDiagnostics(
                new AzureAppServicesDiagnosticsSettings
                {
                    OutputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss zzz} [{Level}] {RequestId}-{SourceContext}: {Message}{NewLine}{Exception}"
                }
                );

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }

然后在HomeController.cs中添加以下代码:

        private readonly ILogger _logger;
        public HomeController(ILoggerFactory loggerFactory)
        {
            _logger = loggerFactory.CreateLogger<HomeController>();
        }

        public IActionResult Index()
        {
            _logger.LogInformation("This is a Log information!!!");
            _logger.LogError("This is a Logger error!!!");
            return View();
        }

2.After发布到azure,在azure portal -> web app -> App service logs,设置blob存储。截图如下:

3.Run web,查看指定blob存储中的日志: