Logging into Console in ASP.NET Core MVC Application

One of the important upgrades happened in .NET Core is the complete rewrite of the diagnostic logging pipeline which emits different events for logging errors. .NET Core now supports logging framework out of the box and also supports extensibility to make use of third party logging frameworks such as Log4Net, NLog etc. Logging can be implemented in quick time with a minimal amount of code in your application.

Microsoft uses Microsoft.Extensions.Logging namespace for implement logging functionality and acts a wrapper for third party logging frameworks. This eradicates the need of writing our own logging framework to provide abstraction for third party frameworks such NLog, Log4Net etc. Also it has got inbuilt providers for supporting logging into Console, Event log, Trace Logging etc.

Console logging in ASP.NET Core MVC application.

As I said earlier logging has got inbuilt support provided by the ILogger class in .NET Core. For that, first we need to add a reference to the Microsoft.Extensions.Logging package in project.json file. Add the following entries under dependencies section in the json file for implementing providers for console and debug logging. 

"Microsoft.Extensions.Logging": "1.0.0-rc2-final",
"Microsoft.Extensions.Logging.Console": "1.0.0-rc2-final",
"Microsoft.Extensions.Logging.Debug": "1.0.0-rc2-final",

Now we will configure the framework in the Configure method in Startup.cs file. Here we are going to inject the instance for the ILoggerFactory using Dependency Injection(DI) which is now supported out of the box in .NET Core. Then inside that, we will call the AddConsole method to set up logging into the console in our application. Here I have hooked up the Debug logger too which will write logging information in the output window if you are running the project from Visual Studio. 

  public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole();
            loggerFactory.AddDebug();

            //omitted rest of the code for brevity
        }

Let's fire up our sample project using the dotnet run command which will compile the web application and self host it at port #5000 by default. If you access the a page in the browser, the console will show all the information which is available in the logging pipeline.

 

In one of the earlier posts, I have showed you the use of StatusCodePages middleware in an .NET CoreMVC application to handle page not found errors. I am going to resue that example for showing you how to implement the logger in the controller for logging information or errors.

The first step is to inject the instance of ILogger into the controller and then assign it to a local variable so that we can access it in all the methods in the controller.

ILogger _logger;

public ErrorController(ILogger logger)
{
   _logger = logger;
}

To log the information into the console we will invoke the LogInformation method as shown below

[Route("/Error/{ErrorCode}")]
public IActionResult Error(int ErrorCode)
{
     var moreInfo = HttpContext.Features.Get();
     _logger.LogInformation("Error occurred with Status Code : {StatusCode}",ErrorCode);
     return View(ErrorCode);
}

Let's compile and run the application to see how the information is logged in the console. Try accessing a non existing page in your application and you will see the above message logged in the console as shown in the  higlighted portion in the image.

For handling this error, I used the UseStatusCodePagesWithReExecute method in the StatusCodePages middleware. When this method is used, the middleware adds a collection to the FeatureCollection object in the HttpContext object. So let's use that collection to log more information in the console, the statement given below will include the original path along with the message so that end user will be able to identify the source of the error.

_logger.LogInformation("Error occurred with Status Code : {StatusCode}, Original Path : {Original Path}",
ErrorCode, moreInfo.OriginalPath);

Let's recompile the application and see what is getting logged in the console while trying to access an incorrect page.

As you can see from the image, you can see that the error message has now got the original path along with the error message and status code.

Here's the full source code

Error Controller

Startup.cs

project.json - dependencies


No Comments

Add a Comment