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.

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 )

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: