Azure Service Bus Queue with MassTransit


Reading time: 13 minutes

Description

In this post I will explain how to create a bus queue and consume it. The case study would be around the order system. Let’s imagine a system where you can create a new order for whatever reason in the industry you like. This could be an e-commerce website, an airplane or bus ticket ordering website.

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.

This project is going to be our Sender according to Microsoft resources or Producers according to Masstransit documentation.

In the same solution add New Project and select Class Library (.Net Standard) This project will contain our Contracts. You can read a definition for it here or here.

The reason why we add the class library of Net Standard is because it provides a uniformity in the .Net ecosystem. In other words if you got two projects of different .Net platform versions(.Net Framework 4.5 and .Net Core 3.1) thanks to .Net Standard these would be able to share a particular class library without any issues.

Now we need to add a Consumer or Receiver. In essence this is where our message would end up going. Or you can process it and send it further where you want to.

Add a new web app project to this solution and select Empty template.

Next thing is to add several Nuget packages

We need to install several MassTransit related packages in addition to Azure Service bus.

Required packages:

Right click on the project and select Manage Nuget Packages. In that tab search for each of these packages and install them to Sender and Consumer projects.

Installed Nugets should look like this.

Next thing we would be adding the code to send and consume message

In the Controller folder of the Sender project add a new controller. I will call it OrdersController. Next add the HttpPost method NewOrder.

Action method should look like this.

    [HttpPost()]
        public async Task<IActionResult> NewOrder()
        {
            var sendEndpoint =
             await _sendEndpointProvider.GetSendEndpoint(
                 new Uri("sb://servicebusqueuesnetcore.servicebus.windows.net/new-orders"));

            await sendEndpoint.Send(
                                        new Order
                                        {
                                            OrderId = Guid.NewGuid(),
                                            Timestamp = DateTime.UtcNow,
                                            PublicOrderId = _random.Next(1, 999).ToString()
                                        });

            return Ok();
        }

We also need to add a contract. In the Contracts project add a new class and call it Order. Add all properties that you require. It should look like the example below.

public class Order
    {
        public Guid OrderId { get; set; }
        public string PublicOrderId { get; set; }

        public DateTime Timestamp { get; set; }
    }

Let’s go back to the Sender project and open the Startup file. In it we will add a service bus, MassTransit, register and define endpoints.

In there we need to edit the ConfigureServices method in order to add required services to the DI container.

This is how it should look like.

 public void ConfigureServices(IServiceCollection services)
        {
            var connectionString =
        "Endpoint=sb://servicebusqueuesnetcore.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=blablasharedaccesskey";

            var newOrdersQueue = "new-orders";

            // create the bus using Azure Service bus
            var azureServiceBus = Bus.Factory.CreateUsingAzureServiceBus(busFactoryConfig =>
            {
                busFactoryConfig.Host(connectionString);

                // specify the message of Order object to be sent to a specific queue
                busFactoryConfig.Message<Order>(configTopology =>
                {
                    configTopology.SetEntityName(newOrdersQueue);
                });
            });

            services.AddMassTransit
                (
                    config =>
                    {
                        config.AddBus(provider => azureServiceBus);
                    }
                );

            services.AddSingleton<ISendEndpointProvider>(azureServiceBus);
            services.AddSingleton<IBus>(azureServiceBus);

            services.AddControllers();
        }

Next we need to perform a similar sort of changes in the Consumer project.

Add a new class and call it OrderConsumer. Inside let’s add some code.

  public class OrderConsumer 
        : IConsumer<Order>
    {
        public Task Consume(ConsumeContext<Order> context)
        {
            System.Threading.Thread.Sleep(60000);//Wait for one minute

            //by returning a completed task service bus removes message from the queue
            return Task.CompletedTask;
        }
    }

Next let’s add HostedService that would start and stop our service bus. It’s very important to start service bus before attempting anything.

Add a new class and call it BusHostedService.

public class BusHostedService
        : IHostedService
    {
        readonly IBusControl _busControl;

        public BusHostedService(
            IBusControl busControl)
        {
            _busControl = busControl;
        }

        public async Task StartAsync(CancellationToken cancellationToken)
        {
            await _busControl.StartAsync(cancellationToken);
        }

        public async Task StopAsync(CancellationToken cancellationToken)
        {
            await _busControl.StopAsync(cancellationToken);
        }
    }

Next it’s Startup files turn. Similar changes as for Sender Startup. We need to configure services that would be available through Dependency Injection.

Note: Queue name should match between Sender and Consumer.

 public void ConfigureServices(IServiceCollection services)
        {
            var connectionString = "endpoint of your service bus";
            var newOrdersQueue = "new-orders"; // need to make sure the queue name is written correctly

            services.AddMassTransit(serviceCollectionConfigurator =>
            {
                serviceCollectionConfigurator.AddConsumer<OrderConsumer>();

                //Consumers - Receivers
                //Message Creators - Senders
                //would normally be in different applications

                serviceCollectionConfigurator.AddBus
                    (registrationContext => Bus.Factory.CreateUsingAzureServiceBus
                                                    (configurator =>
                                                    {
                                                        configurator.Host(connectionString);

                                                        /*
                                                         For a consumer to receive messages, the consumer must be connected to a receive endpoint. 
                                                        This is done during bus configuration, particularly within the configuration of a receive endpoint.
                                                        https://masstransit-project.com/usage/consumers.html#consumer*/

                                                        configurator.ReceiveEndpoint(newOrdersQueue, endpointConfigurator =>
                                                        {
                                                            endpointConfigurator.ConfigureConsumer<OrderConsumer>(registrationContext);
                                                        });
                                                    }
                                                    )
                     );

            });

            //need to always start the bus, so it behaves correctly
            services.AddSingleton<IHostedService, BusHostedService>();
        }

Next thing we need to create Azure Service Bus

For this we need to go to Azure Portal home. Select Create a Resource.

On the next screen choose Integration then in the right pane menu Service Bus.

When you are creating Service Bus the things to consider are Resource group, Location and Pricing tier.

For Resource groups either create a new or select the existing one. If it’s part of existing then you can manage it with other resources in that group.

Normally Location should be local to you as different regions/locations have different regulations, latency etc. You can either use the same region or pair them. For example your web app uses UK South, so you would consider using UK South instead of East US for your service bus. If you are pairing then consider using UK South and UK West.

However there are no limits as to what region and location to use. As long as it answers your personal or business requirements. You can read more about regions here and here.

If you consider using different regions then check out this Microsoft article.

As for the tier let’s use the Standard pricing tier since it always works and it’s easier to set up.

Note: Azure charges money for this tier. So make sure you use it accordingly and delete the service bus once you stop playing with it.

Once it’s successfully deployed we need to go and retrieve the connection string for our application. Go to the resource and select the service bus namespace.

On your service bus find Settings and select Shared access policies. Then select RootManageSharedAccessKe and copy Primary Connection String.

We need to paste the whole string into the connectionString variable value in the Startup file of Sender and Consumer projects.

Next let’s test what we created

Since we have Sender and Consumer in the same solution we need to set this solution to run multiple projects. Right click on the solution, select radio button for Multiple startup projects. From the dropdown of Action columns select which projects to run.

To simplify things disable SSL for Sender and Consumer projects. On the Sender project right click and select Properties. In the newly opened tab select Debug and find Enable SSL checkbox. Untick it and save it.

Run the solution.

Because we need to hit HttpPost method we would require some sort of API client tool. For this example let’s try out Postman.

Let’s grab the URL of our Sender project and put it into the Postman tab with HttpPost method type selected. We also need to prefix it with controller route.

http://localhost:58852/api/orders

It should return Status 200 OK if everything went ok.

Next let’s check our Azure Service Bus on Azure portal

If you go back to azure portal and open our service bus namespace. Every time you hit the HttpPost method a message will be enqueued. The consumer will process it when it will become available. One of the message models of Azure Service Bus Queues is First in, First out(FIFO).

As you can see our Queue has been added. If you click on it you would be able to see some stats and message count.

Because we suspend current thread for a minute the Consumer will process each new message once this time has passed. So if you hit that HttpPost method several times all these messages will be added to our queue one by one. However the message will start to process after one minute from the moment it was added.

public Task Consume(ConsumeContext<Order> context)
        {
            System.Threading.Thread.Sleep(60000);//Wait for one minute

            //by returning a completed task service bus removes message from the queue
            return Task.CompletedTask;
        }

By returning a completed task this message will be removed from the queue.

Before we wrap up we need to tidy things up

This is especially the case because we are using the Standard pricing tier for this Service Bus namespace.

There are several options as to how to do it.

You can delete the Service Bus namespace on the page itself.

Another option is to delete a Resource group altogether.

Conclusion

Azure Service Bus is a cloud messaging service. What is appealing is the simplicity of use and set up. What makes it even more easier is the addition of MassTransit, a distributed application framework which is responsible for abstracting the transportation.

By using these tools correctly you are able to achieve service decoupling with no sweat. There are other reasons to use it. To name a few, the application scaling, asynchronous processing and monitoring.

Source code

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.

Logging to Azure Blob Storage


Reading time: 8 minutes

Description

In this post I will explain how to set up logging for Net Core Web App with 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.

On the next window give your application a name and choose where to save it.

For this application select API template.

Next thing is to add Nuget package for Azure App Service Logging

Right click on the project and select Manage Nuget Packages. In that tab search for Microsoft.Extensions.Logging.AzureAppServices

Next we need to modify Program.cs file

By doing so we are adding logging to our application that would be monitored with Azure App Service for this application.

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureLogging(logging =>
                {
                    // To override the default set of logging providers added 
                    // by Host.CreateDefaultBuilder, call ClearProviders
                    logging.ClearProviders();
                    // add the required logging providers
                    logging.AddAzureWebAppDiagnostics();
                })
                .ConfigureServices(serviceCollection =>
                    serviceCollection //configure Azure Blob Storage
                        .Configure<AzureBlobLoggerOptions>(options =>
                        {
                            //set the last section of log blob name
                            options.BlobName = "log08062020.txt";
                        })
                )
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });

This is how the Program.cs file should look like. When we set the BlobName it is only for the last section of the name. Hence the actual name in blob storage would look something like blabla12345_log08062020.txt

Next we need to edit generated controller code

If you have chosen the API template in previous steps then this part should be a one liner code. The controller should already have an ILogger interface injected to the controller constructor. Our task is to add some code in the HttpGet method that will call ILogger method to write a log message.

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

Next let’s publish our application and create Azure Storage at the same time

For this we need to right click on the project and select Publish. Then you should see the Publish pop out window. There, select Azure.

On the next pop out select Azure App Service (Windows).

On the next window check your Subscription. Then click Create a new Azure App Service.

On the next window add a new Resource group and Hosting plan.

Once you have set up everything click Finish.

This is what you should see next.

We need to add Azure storage as dependency to our application. So click Add.

On the pop out select Azure Storage.

And then Create a storage account.

On the next pop out we need to select the resource group that we have added in previous steps when we create a new Azure App Service. It should be NetCoreAzureBlobLogging20200608171456Resource This way we got both web application and storage in the same group. This helps to keep things organized, you can work with them together, delete them together and so on.

For an Account type select Standard – Locally Redundant Storage. Locally redundant storage (LRS) copies your data synchronously three times within a single physical location in the primary region. LRS is the least expensive replication option, but is not recommended for applications requiring high availability.

Select our newly created storage instance and click Next.

Add connection string name, leave option to save connection string as Azure App Settings.

Finally you should see something similar. In order to actually publish you need to click the Publish button. Nothing complex but sometimes you can get distracted by so many steps and forget to actually click it. But you are clever and won’t get caught doing this.

Once it is successfully published a web page should open. Alternatively we can use Site URL in the browser of your choice. Or even we can go to Azure portal home, click on Resource Groups, then find your group created in previous steps and select App Service for our web application.

Next step is to enable logging to Azure Blob Storage

On the Azure App Service page for our web application go to the Monitoring section of left the pane menu. In there select App Service logs. Switch On Application Logging (Blob), set Level to Information, Retention Period to 1 and then click on Storage Settings.

In the next window select our blob storage account and create a container.

Let’s manually test what we got

For this you can use any Api client or debugging tool e.g. Postman, Fiddler etc However in our case because it’s a HttpGet method we can use any browser.

Put our Azure App Service web application Url into the address bar of a web browser, prefix it with /WeatherForecast as the name of our controller and hit Enter. Like it is shown below.

https://netcoreazurebloblogging20200608171456.azurewebsites.net/WeatherForecast

This is what you should see.

Next we need to go to the Blob Storage container section of Azure portal. You can find it either under the same Resource Group or you can access it through Azure portal home page.

From there click on Containers

Then you need to go all the way to our Log file location.

There should be a Download button.

Once the download has completed you can inspect the Log text file and see our logged message from the controller.

Before we wrap up we need to tidy things up

It is a good habit to stop or delete your created service once you finish playing with them. This way you would prevent any service charges. If you go back to the Resource Group section of Azure portal and select your one. On the details page of that Resource you can delete it together with all the services under it.

Conclusion

As you have noticed, for a basic setup of logging you really need to do a few steps. And again it is mostly downloading a particular Nuget package, adding a few lines of code to Program or Startup files, creating an Azure storage account and there you go!

If you want something tangible that can be applied to real world applications I recommend to looking into Structured logging.

Have fun exploring and stay tuned!

Logging Net Core App to Console

Reading time: 7 minutes

Description

In this post I will explain how to set up logging so that output messages show in the Console. There will be two options of how to do it. One in Console Application and the other with Web Application that is run as a project.

What is required

  • Visual Studio
  • Net Core Console App
  • Net Core Web App

Let’s start by creating a Net Core Web App

Open Visual Studio and choose ASP.NET Core Web Application.

Add Project name and location for this application.

Then select API for project template.

Next step is to edit Program.cs file

We need to edit a code that builds a host object. In essence it is a place where everything gets set up i.e. DI, Logging, Configuration, IHostedService implementations.

For this tutorial we are interested in Logging only.

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureLogging(logging =>
                {
                    // override the default set of logging providers added by Host.CreateDefaultBuilder
                    logging.ClearProviders();

                    // add the required logging providers
                    logging.AddConsole();
                })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });

Below is how your Program.cs should look like.

Now let’s see what we made here

Before running the application for the first time we need to edit Debug Profile. First set it to our project name NetCoreLoggingConsole and then set it to launch as Project.

Now if we Run/Start Debugging the application we should see a Console Application window to appear. On startup it hits the Get method of the controller and as a result logger logs Information Log Level message. It then appears in the Console Application window. To note you need to make sure you got the ILogger interface into the constructor of the controller.

More closer image.

We can achieve the same result in the Console Application

Let’s add a new project Console Application to this solution. Right Click on the Solution name.

Select Console App (.Net Core)

Let’s configure necessary bits to add Logging to this application. For that we need to install the Microsoft.Extensions.Logging.Console nuget package.

After the nuget package is installed, let’s open Program.cs for this new project and add some code inside the Main method.

//net core default DI
            var serviceProvider = new ServiceCollection()
                .AddLogging(builder => builder
                                    .AddConsole()
                                    .SetMinimumLevel(LogLevel.Debug))
                .BuildServiceProvider();

            //create logger instance
            var logger = serviceProvider
                                .GetService<ILoggerFactory>()
                                .CreateLogger<Program>();

            logger.LogInformation("CONSOLE -> Main method");

            Console.WriteLine("Hello World!");

            Console.ReadLine();

This is how it should look like once everything is in place.

Next step is to set to run multiple projects for this solution.

There you go a closer look.

As a result we should see two Console Application windows. If you remember one for Web Application that is run as Project and one for Console Application.

And closer look.

Conclusion

Logging to Console can be handy. Normally you would develop small programs for practice purposes. However with Net Code you can implement more advanced stuff like add DI, host object, configuration etc

As a result you can have a Console Application based microservice to do a particular job. It is straightforward to set up and you can quickly develop applications following this pattern.

What is great is that you can add just necessary stuff and develop around it.

Logging Net Core App to Debug window

Reading time: 3 minutes

Description

In this post I will explain how to setup logging so that output messages shows in one of the debug windows i.e. Output.

What is required

  • 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.

Then add the name and specify the location.

As for template select Web Api.

Next step is to edit Program.cs file

We need to edit a code that builds a host object. In essence it is a place where everything gets set up i.e. DI, Logging, Configuration, IHostedService implementations.

For this tutorial we are interested in Logging only.

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureLogging(logging =>
                {
                    // override the default set of logging providers added by Host.CreateDefaultBuilder
                    logging.ClearProviders();

                    // add the required logging providers
                    logging.AddDebug();
                })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });

Below is how your Program.cs should look like.

Next step is to edit a logger code

Open up generated controller file. Make sure you got ILogger injected through a constructor. Then add the logger LogInformation method to the controller Get method.

As part of this step let’s add am Output window. Go to View -> Output and this should show an Output Tab.

Next thing is to Debug this app

Make sure you got Debug Configuration selected. Then either click F5 or Click the IIS Express button. Also for convenience sake untick Enable SSL for this web project in project Properties.

As you can see in the image the Output window shows our logger message.

Conclusion

Since Net Core SDK has a default Logging provider it is very easy to log stuff.

Logging is a powerful tool when dealing with development issues. Moreover it is a friend to a programmer. Because with the correctly used logging approach you have more information regarding running processes in your application.

Normally after analyzing logs you can get a hint as to where to look for bugs. It could be a real time saver.

Logging Net Core App to Azure App Service logs Filesystem

Reading time: 8 minutes

Description

In this post I will explain how to setup logging for Net Core Web App with logging messages to be monitored on Azure App Service.

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.

Then add the name and specify the location.

You can select whatever web application template you want. To keep the habit of using a modern framework for frontend I will select an Angular template.

Next thing is to add Nuget package for Azure App Service Logging

Right click on the project and select Manage Nuget Packages. In that tab search for Microsoft.Extensions.Logging.AzureAppServices

Next we need to modify Program.cs file

By doing so we are adding logging to our application that would be monitored with Azure App Service for this application.

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureLogging(logging =>
                {
                      // To override the default set of logging providers added 
                      // by Host.CreateDefaultBuilder, call ClearProviders
                      logging.ClearProviders();
                      // add the required logging providers
                      logging.AddAzureWebAppDiagnostics();
                })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });

This is how the Program.cs file should look like.

What you need to decide is the Log level that you will be logging. One of the main things with logging is making sure you are logging the appropriate information. For instance Debug level would be too much for production. Moreover it can expose some sensitive information. The amount of logging in production should only be necessary information which would not affect the performance of the application. More information here.

For this case let’s leave default settings in place. This means Information log level will be logged.

Let’s modify an existing controller that was created for us. Make sure you got ILogger injected to your constuctor. ILogger comes with Net Core SDK and this is a minimum you need to do.

Next step is to Publish this application to Azure App Service

Same as when you added Nuget package in the previous step right click on the web application project and select Publish.

On the next screen select Azure.

Then select Azure App Service (Windows).

On the next screen select the appropriate subscription. After that click on Create a new Azure App Service.

On newly opened pop out select your subscription. For the Resource group and Hosting Plan add new ones. In my case since I am on a Free Subscription I will choose a free tier plan.

After you click Create the pop out will close and you will get back to the App Service details window with the new Resource group selected. Click Finish.

On the Publish tab you need to find the Publish button and click it. This will actually trigger the Publish process. You are also provided with a URL for this app. Once the app is published you will be able to see your active app.

You can monitor publish progress in Visual Studio Output window.

Next step is to activate logging on Azure

Go to azure portal home and select App Services.

On the next page select the name of your newly created App Service. In my case it will be NetCoreAzureLogging20200601230511

On that page scroll to the Monitoring section and select App Service logs.

Use the toggle button and move toggle to option On. For Level choose Information. Click Save.

Alright let’s manually test what we made here. Since it’s a HttpGet Api method we can use any browser. Enter web app URL into address bar with controller name prefix. It should read yourAppServiceUrl/yourControllerName. In my case it is

https://netcoreazurelogging20200601230511.azurewebsites.net/WeatherForecast

If we go back to the Azure portal to your App Service. Scroll to Monitoring and select Log Stream.

Once you are there you should see a line with Information Log level with the message we added to the controller.

Conclusion

As you can see setting up Azure logging is quite simple. What is more important is to think what level to log, where to store it and what exactly is required for each environment.

Logging is one of those things that can help you and on the other hand be a culprit of slower application.

It is certainly useful to have with every application as this would be an additional assistance for any case that requires monitoring. So please use it with caution.