如何在Azure for Net Core 2 App中启用应用程序日志?

时间:2017-10-29 03:59:03

标签: c# azure logging asp.net-core-2.0

我正在尝试在azure中启用应用程序日志。 我在azure的appService中运行了一个虚拟Net Core 2应用程序。

基本上我的目标是在日志流和应用程序日志文件中查看跟踪消息,但我没有找到正确的方法来执行此操作。

我发现阅读其他帖子的挑战之一是他们假设有一个网络配置。

Home Controller   Configuration In Azure   Startup.cs

4 个答案:

答案 0 :(得分:1)

你可以从这个blog得到答案。以下是博客的摘录。

  

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

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

enter image description here

答案 1 :(得分:1)

您需要使用“Microsoft.Extensions.Logging.AzureAppServices”包,然后使用以下代码注册azure的日志记录提供程序。

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

答案 2 :(得分:1)

ASP.NET Core 2.2的文档为here

首先,启用“应用程序日志记录”并选择适当的级别:

switch on application logging

这可能是诊断任何问题所需要做的。但是,如果要查看日志消息,请安装Microsoft.Extensions.Logging.AzureAppServices NuGet程序包。

然后,配置日志记录:

using Microsoft.Extensions.Logging;

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
    .ConfigureLogging(logging =>
    {
        logging.AddAzureWebAppDiagnostics();
    })
    .UseStartup<Startup>();

现在您可以注入并使用ILogger:

public Startup(IConfiguration configuration, ILogger<Startup> logger)
{
    Configuration = configuration;
    this.logger = logger;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    logger.LogWarning("Starting up");

然后在Azure App Service中,单击“日志流”: Log stream

答案 3 :(得分:0)

运行dotnet add package EntityFramework Microsoft.Extensions.Logging.AzureAppServices,将日志记录扩展名安装到您的项目中。

Program.cs文件供参考:

public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
             .ConfigureLogging((hostingContext, logging) =>
             {
                 logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                 logging.AddConsole();
                 logging.AddDebug();
                 logging.AddAzureWebAppDiagnostics();
             })
            .UseApplicationInsights()
            .UseStartup<Startup>()
            .Build();
}