Monday, April 6, 2020

Asp.Net Core Console logging

In the previous post we saw the various Interfaces and Classes provided by Asp.Net Core to support logging, in this post we shall see on how to enable Console logging in an Asp.Net Core Web API application.

To enable a specific type of log we need to add the log provider to the startup. To add a provider we need to call the provider's Add extension method under ConfigureLogging in Program.cs. To Add a console log provider we need to add the following to the Program.cs
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .ConfigureLogging(logging =>
                {
                    logging.ClearProviders();
                    logging.AddConsole();
                });
    }

Once we setup the log provider, we can create an instance of the Logger in the controller class and call its log methods as follows.

[Route("api/[controller]")]
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        private readonly ILogger _logger;
        public EmployeeController(ILogger<EmployeeController> logger)
        {
            _logger = logger;
        }

        //// api/Department/GetDepartments
        [HttpGet("GetEmployeeDetails")]
        public ActionResult<List<EmployeeDetail>> Get()
        {
            _logger.LogInformation("Entering GetEmployeeDetails");
            . . .
            _logger.LogInformation("GetEmployeeDetails Succesful");
        }
    }

If we run the Application from Visual Studio then the console logs can be viewed in the output window as follows.




Search Flipkart Products:
Flipkart.com

No comments: