Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am trying to enable application logs in azure. I have a dummy Net Core 2 App running in an appService in azure.

and basically my goal is to see the trace messages in the log stream and in the application log files but I have not found the right way to do this.

One of the challenge I have found reading other posts is that they assume a web config in place.

Home Controller Configuration In Azure Startup.cs

like image 634
Wilson Avatar asked Oct 29 '17 03:10

Wilson


2 Answers

The documentation for ASP.NET Core 2.2 is here.

Firstly, enable Application Logging and choose the appropriate level:

switch on application logging

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: Log stream

like image 62
Matt Frear Avatar answered Oct 12 '22 00:10

Matt Frear


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();
}
like image 3
Emre Avatar answered Oct 12 '22 00:10

Emre