Home » C# » How to setup logging in ASP.Net Core and Azure

How to setup logging in ASP.Net Core and Azure

I hadn’t had to set logging up for a while in any .Net project and then I was faced with a .NET core API project and a requirement for logging both locally and in an Azure deployment environment. .Net core has built in support for logging, but be aware that it does not support logging to a file, for that you would need a third party logger. It does, though, enable different level log messages and shows all of those messages in the console window. It’s also pretty straightforward to set up logging in ASP .Net Core and Azure, although you wouldn’t think so from some of the documentation out there! My requirement was to be able to use log messages locally and to be able to use them in Azure – each part needs setting up.

FYI – by default, ASP.NET Core uses the class name of the code logging an event as the event’s category.

Setting up .Net Core logging in your project

Setting up logging requires you to :

  1. Install the Microsoft.Extensions.Logging.AzureAppServices Nuget package
  2. Add a Logging section to the appsettings.json file. If you want to log all requests, even without using the “logger” in .Net, modify the default appsettings.Development.json file that’s automatically created, and change the value for “Microsoft” under “LogLevel” from “Warning” to “Information
{
  "Logging": {
    "LogLevel": {
      "Default": "Debug",
      "Microsoft": "Information",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  }
}

3. Add a ConfigureLogging property to the CreateHostBuilder method in Program.cs.

public static IHostBuilder CreateHostBuilder(string[] args) =>
     Host.CreateDefaultBuilder(args)
		.ConfigureLogging(builder => builder.AddAzureWebAppDiagnostics())
        .ConfigureWebHostDefaults(webBuilder =>
        {
        	webBuilder.UseStartup<Startup>();
        });

4. Change settings in the AppService > Monitoring > App Service Logs page. More specifically, click on your App Service from the list, then click the App Service Logs button from the Monitoring section. Now you need to switch on Application Logging (Filesystem) and select the level of messages you want to see.

How to View log messages locally

In Visual Studio view the Output window (View > Output or press Ctrl + W,O) and from the drop down select the option that has your project name in it. You’ll see your log messages here.

How to view log messages in Azure

Click on your App Service from the list, then click the Log Stream button from the Monitoring section, you will start to see your log messages show up here.

And that’s it – you have now setup logging in your ASP.Net core project, you can view the log messages locally, and you can view the log messages in Azure.