Logging to Azure Blob Storage with Serilog


Reading time: 6 minutes

Description

In this post I will explain how to set up logging for Net Core Web App with Serilog and logging messages to be stored in Azure Blob Storage.

What is required

  • Azure Subscription
  • Visual Studio
  • Net Core Web App

Let’s start by creating a Net Core App

Open Visual Studio and choose ASP.NET Core Web Application. Choose an API project template.

At the same time let’s modify the generated controller. Make sure the ILogger interface is injected and there is a readonly property that we can use within controller methods. Add this line of code within HttpGet method.

_logger.LogInformation("INFORMATION -> WeatherForecastController");

Next thing is to add two Nuget packages

Right click on the project and select Manage Nuget Packages. In that tab search for Serilog.AspNetCore This package is required to use ILogger interface along with Serilog within your methods. Since Asp Net Core has a built in logging framework this Nuget would allow you to plug-in into logging infrastructure.

Additionally we need Serilog.Sinks.AzureBlobStorage in order to write to the blob storage file. Serilog uses sink concept for various providers. Sink in computing in essence is a class that receives or consumes call/incoming requests from another object.

Next we need to modify Program.cs file

Serilog method requires a connection string from your blob storage to be provided as an argument. Plus we need to add UseSerilog() as an extension to the CreateHostBuilder method. This way we set Serilog as the logging provider.

 public static void Main(string[] args)
        {
			var connectionString = "DefaultEndpointsProtocol=https;AccountName=serilogblobloggingname;AccountKey=blablablakey;EndpointSuffix=core.windows.net";

			Log.Logger = new LoggerConfiguration()
							.WriteTo.AzureBlobStorage(connectionString)
							.CreateLogger();

			try
			{
				CreateHostBuilder(args).Build().Run();
				return;
			}
			catch (Exception ex)
			{
				Log.Fatal(ex, "Error while creating and building generic host builder object");
				return;
			}
			finally
			{
				Log.CloseAndFlush();
			}
		}

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

Below is how the Program.cs file should look like. For the connection string we firstly need to create a Storage account in Azure. You can find how to do it below.

Next we need to create blob storage in Azure portal

Go to Azure portal home and click on Storage Accounts.

On the next page click Add, so you would end up on this page. For storage account overview check this article

When filling out the Create Storage Account form pay attention to Performance, Account kind, Replication and Access tier fields as these might affect the performance and running costs of your storage account.

Once it’s created go to Settings for this storage account and click on Access Keys. We need to get the Connection string for our application.

Copy this connection string and go to our application Program.cs. Find the section that has a connectionString variable and replace it with your copied value.

var connectionString = "DefaultEndpointsProtocol=https;AccountName=serilogblobloggingname;AccountKey=blablaConnectionString;EndpointSuffix=core.windows.net";

			Log.Logger = new LoggerConfiguration()
							.WriteTo.AzureBlobStorage(connectionString)
							.CreateLogger();

Next let’s test what we created

Let’s run our application. This application out of the box should hit HttpGet method without changing anything. You can double check this in launchSettings.json or simply go to the web browser after running the app and make sure it has a weatherforecast prefix at the end of the Url.

For me it’s going to be:

http://localhost:64861/weatherforecast

If everything is fine and you got your app running then we need to go to Azure portal to check the logs.

Next let’s check the logs on Azure portal

Go to Azure portal, Storage Accounts and find your storage account. On the overview page click on Containers.

On the next view you should see your container with logs.

Click on it and you should see a log.txt file with an option to Download when you click on it. Download it and check the results.

Awesome job!

Before we wrap up we need to tidy things up

Once you’ve finished playing with your Storage Account it’s better to delete it. You can delete it from it’s main page.

Or if it’s part of the Resource Group then you can delete the whole group.

Conclusion

Setting up logging for Azure Blob Storage with Serilog as easy as to do it just with Microsoft.Extensions.Logging.AzureAppServices Nuget package.

Few modifications to the code, up and running storage account and you are all good.

Of course developers choose third party libraries/platforms like Serilog, NLog and others for different purposes. Normally it’s about the extended features and simplicity of use that these provide. Also the additional support in means of documentation and code examples that you can get.

2 thoughts on “Logging to Azure Blob Storage with Serilog”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: