How to enable Application Logs in Azure for Net Core 2 App?

谁都会走 提交于 2019-12-05 06:03:04

The documentation for ASP.NET Core 2.2 is here.

Firstly, enable Application Logging and choose the appropriate level:

This may be all you need to do to diagnose any problems. But if you want log messages and see them, install the Microsoft.Extensions.Logging.AzureAppServices NuGet package.

Then, configure logging:

using Microsoft.Extensions.Logging;

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

Now you can inject and use 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");

Then in the Azure App Service, click on Log stream:

You could get answer from this blog. The following is the snippet from the blog.

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();

You need to use "Microsoft.Extensions.Logging.AzureAppServices" package and then register the logging provider for azure using code below.

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

Run dotnet add package EntityFramework Microsoft.Extensions.Logging.AzureAppServices to install logging extension to your project.

Program.cs file for reference:

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();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!