且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ASP.NET Core应用程序日志未写入Azure App Service中的Blob

更新时间:2023-02-15 18:43:19

如果要将应用程序日志写入Azure blob存储,首先需要在Azure门户上启用应用程序日志并为其配置blob存储.

If we want to write Application logs to Azure blob storage ,firstly we need to enable Application log and configurate blob storage for it on the Azure portal.

我们可以关注博客来设置Asp.net核心应用中的日志记录.

We could following the blog to set up logging in the Asp.net core app.

在ASP.NET Core应用中设置日志记录不需要太多代码. ASP.NET Core新项目模板已经使用Startup.Configure方法中的以下代码设置了一些基本的日志记录提供程序:

setting up logging in an ASP.NET Core app doesn’t require much code. ASP.NET Core new project templates already setup some basic logging providers with this code in the Startup.Configure method:

loggerFactory.AddConsole(Configuration.GetSection("Logging")); 
loggerFactory.AddDebug();

我也为此做演示.它在我这边正常工作.

I also do demo for it. It works correctly on my side.

1.在Sartup.cs文件中添加以下代码

1.In the Sartup.cs file add the following code

 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}",

                }
            );

2.在HomeController.cs中添加以下代码

2.add following code in the HomeController.cs

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

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

3.访问主页/索引页面,然后从Azure存储Blob中对其进行检查.日志Blob名称的最后一部分.默认为" applicationLog.txt ".我们也可以将其设置为自己.

3.Visit the home/index page and check it from the Azure storage blob. Last section of log blob name. Defaults to "applicationLog.txt". We also could set it ourseleves.