Logging in ASP.NET Core

In this article, we will learn about the build-in logging console provider, how they are configured and how can you use them


Let's use the .NET cli to create a new ASP.NET Web API application


- Open Command Prompt ( cmd.exe )


- Type the following code snippet. This is going to create a new web api application into the current folder


> dotnet new webapi 

logging_aspnetcore_2.PNG

Let's open this application in an IDE. We will choose Visual Studio Code in this example.


- To open Visual Studio Code, type the following code snippet.


> code .

The project is loaded here


logging_aspnetcore_1.PNG

Let's first create a log in this template. To do that, let's go to the WeatherForecast controller.


In the constructor, we see that we have an ILogger. However this is not getting used at the moment.


- Type the following code snippet.


	_logger.Log(LogLevel.Information, "Hello World");

- Put the breakpoint as shown below.


- Run this application to see how this works. After the application has started, it has automatically called the WeatherForecast endpoint. (https://localhost:5001/WeatherForecast)


We have the breakpoint and it's calling the _logger.Log method. Let's step into it and go to the console to see that particular message coming up in the console.


logging_aspnetcore_3.PNG

We have successfully written a log message


Let's see how this is working and how it started logging into the console


- Stop the application and go to the Program.cs file


We call a Host.CreateDefaultBuilder method that we are using to initialize the builder


By default, ASP.NET Core template is setting up the console provider. This is the reason why we could see this message in the console when we ran the application before.


You can override the default console provider in the Program.cs file.


We can add an extension method which is the ConfigureLogging method. Logging is configured using the ConfigureLogging method as shown below.


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

We call the ClearProviders which will clear all the logging providers(such as console provider)


- Start the application again.


In this case, we should not be seeing the log message in the console. Because we cleared all the providers.


logging_aspnetcore_4.PNG

Now, we're going to add the console provider.


.ConfigureLogging(builder =>{
    builder.ClearProviders();
    builder.AddConsole();
});

- Start the application to see the logging message in the debug console.


logging_aspnetcore_5.PNG

Let's look at what's happenning in the WeatherForecast controller. It takes in an ILogger of WeatherForecastController which is injected in using the dependency injection service.


public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
    _logger = logger;
    _logger.Log(LogLevel.Information, "Hello World");
}

Instead of using the log method and specifying the log level, we can also use the extension methods that's available as part of the Logger class. So we can specify the following code snippet ( _logger.LogInformation("Welcome to howtodevelop.net") ):


public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
    _logger = logger;
    _logger.Log(LogLevel.Information, "Hello World");
    _logger.LogInformation("Welcome to howtodevelop.net");
}

Let's rerun the application. We've used the log information extension method. Let's see how that's represented in the console. You can see a message which is saying "info: Logging.Controllers.WeatherForecastController[0] Welcome to howtodevelop.net"


logging_aspnetcore_6.PNG

Similar to the LogInformation method, we also have extension methods for the other log levels. If we use the log method, we have LogError, LogTrace, LogWarning, LogCritical and LogDebug extension methods.


#aspnetcore #dotnetcore


Each log can have an event id. Event id allows us to group different logging messages. To specify an event id, let's use the log information method and specify an event id. The event id is simply a number that you can specify.



public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
    .
	.
	.
    _logger.LogError(2002, "This is an error");


}


Let's run this and see how the event id appears in the console.


logging_aspnetcore_7.PNG