Logging

The .NET Core app models, such as ASP.NET Core, support logging out-of-the-box. Logging can be enabled by injecting the ILoggerFactory instance through the Configure method of the Startup class, and then using that to add providers. There are a few built-in providers available in the Microsoft.Extensions.Logging namespace. For example, to log information at the Console level, we can call the AddConsole method on the instance of LoggerFactory or AddDebug to log information in the Debug window when the application is running under the debug mode.

Following is the list of logging provider's shipped with ASP.NET Core:

  • Console
  • Debug
  • EventSource
  • EventLog
  • TraceSource
  • Azure App Service

This is the sample code snippet to inject the logger factory instance on the Configure method in the ASP.NET Core application:

    public void Configure(IApplicationBuilder app,
IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
}

Once the logger factory is injected, we have to inject the ILogger instance at the Controller level; we can use methods such as LogInformation, LogWarning, and others to log for different severity levels:

    public class HomeController : Controller 
{
ILogger _logger;

public HomeController(ILogger logger)
{
this._logger = logger;
}
}

In this section, we will not go into the details of how logging can be done. To check that, please refer to Chapter 6, Layered Approach to Solution Architecture.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.79.11