Modern Web Application - Azure App Service ASP.NET Core Logging to Blob Storage
.NET provides very flexible and powerful logging mechanism to write logs into console, files and other destinations. This article show you how to write logs into Azure Blob Storage in your ASP.NET Azure app service application.
Required package
Package Microsoft.Extensions.Logging.AzureAppServices is required to write App services logs into Blob Storage.
You can find more information about this package on NuGet: https://www.nuget.org/packages/Microsoft.Extensions.Logging.AzureAppServices/.
For example, use .NET CLI:
dotnet add package Microsoft.Extensions.Logging.AzureAppServices --version 6.0.1
You can also directly include it in your project file:
<PackageReference Include="Microsoft.Extensions.Logging.AzureAppServices" Version="6.0.1" />
Register the provider
Now you can register this provider in your applications.
For example, the following code snippet uses web host builder method ConfigureLogging function to add Azure web app diagnostics logging provider (logging.AddAzureWebAppDiagnostics).
using Microsoft.AspNetCore;
namespace Kontext.Web.Portals
{
public class Program
{
public static void Main(string[] args)
{
var host = CreateWebHostBuilder(args).Build();
host.Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.AddConsole();
logging.AddAzureWebAppDiagnostics();
});
}
}
You could also configure the settings of this logging provider like file name template, etc. Refer to the source code of AzureBlobLoggerOptions for more details.
Once this logger provider is added, deploy your latest application to Azure.
Enable application logs
Application logging for the Azure app service application must be enabled to log messages. To do that, we can enable it through Azure portal.
- Navigate to the your Azure app service application blade.
- Go to Monitoring->App service logs.
- Enable Application logging (Filesystem) or Application logging (Blob). The main differences is that Filesystem supports streaming logs which can be very useful for live debug of production applications. Filesystem logging will automatically turn off after 12 hours. For this article, we will configure Blob storage for storing logs.
- Configure the options as required:
- Save the changes.
View logs
All the logs can be found in the Azure storage container you have configured.
One thing to notice is that the blob is Append blob which are commonly used for writing logs into storage container. Other blob types are block and page blobs.
The following is one screenshot of Kontext application log:
The logging level I configured is Warning thus only Warning, Error and Critical messages are logged. If you want to store more logs, change the log level to Information or Verbose.