Before we begin…
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()|
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.
How is it working without configuring logging ?
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.
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)|
|public static IHostBuilder CreateHostBuilder(string args) =>|
|webBuilder.ConfigureLogging((hostingContext, loggingBuilder) =>|
|options.IncludeScopes = false;|
|options.TimestampFormat = "hh:mm:ss ";|
|options.JsonWriterOptions = new JsonWriterOptions|
|Indented = true|
If we run the application now, the logs would appear as shown in below snapshot.
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.