Customize Logging Configurations in .NET Core Web Applications

Customize Logging Configurations in .NET Core Web Applications

We have seen how easy it is to configure logging in a .NET console application. In this post, let’s see how to configure logging in an ASP .NET Core web application.

Before we begin…

Let’s create an ASP .NET Core MVC web application using Visual Studio or dotnet CLI.

Once the project is created, open the HomeController.cs file. In the constructor, an ILogger instance is already injected. Let’s try to use it and see if it logs anything.

In the Index action, add few lines of code to log some information. Below snippet shows how the HomeController class should look like:

public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
_logger.LogInformation("Info Log");
_logger.LogWarning("Warning Log");
_logger.LogError("Error Log");
_logger.LogCritical("Critical Log");
return View();
}
}
view raw HomeController.cs hosted with ❤ by GitHub

Now, if you run the application via Visual Studio, and open the Output window and check the output from Debug. It would show the logged information as shown in below snapshot.

Now, stop the application. Open a new Command Prompt or Windows Terminal. Run the application using dotnet CLI command. It would also show the logged statements.

How is it working without configuring logging ?

.NET Core Web App has default providers configured
.NET Core Web App has default providers configured

Why does it work out of the box ?

If we check the Main method of web app, it does not have much code. It just calls Host.CreateDefaultBuilder. This method internally configures logging.

It configures Console, Debug and Event Viewer logging providers for the web application. That’s the reason the application is able to log the messages.

How to change the defaults ?

Now, let’s say, we do not want to use default providers. For our application we want to use console logger (this is highly unlikely for production scenarios, but just for the sake of this demo, let’s consider this).

Now, let’s say, we also want to log the messages in the form of formatted JSON.

For this, we will have to call ConfigureLogging API again and then call ClearProviders to remove all existing providers.

Next, lets add JSON provider and pass the parameters as shown in below code snippet. The option, JsonWriterOptions, is suggesting to write the formatted JSON on console.

public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
webBuilder.ConfigureLogging((hostingContext, loggingBuilder) =>
{
loggingBuilder.ClearProviders();
loggingBuilder.AddJsonConsole(options =>
{
options.IncludeScopes = false;
options.TimestampFormat = "hh:mm:ss ";
options.JsonWriterOptions = new JsonWriterOptions
{
Indented = true
};
});
});
});
}
view raw Program.cs hosted with ❤ by GitHub

If we run the application now, the logs would appear as shown in below snapshot.

Customize logging for .NET Core Web Applications
Customize logging for .NET Core Web Applications

So, we have seen how to customize the default logging configurations in .NET core web applications.

Instead of JSON console provider used in this demo, we can add any of the built-in provider (or third party provider or even custom provider).

Have you already tried this ? Let me know your thoughts.

Leave a Reply