How Logging works in NET Core
Answers (1)
Add AnswerIn ASP.NET Core, logging providers store the logs. You can configure multiple logging providers for your application. The default ASP.NET Core configures the following logging providers: Console, Debug, EventSource, and EventLog (on Windows).
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureLogging(logging =>{ logging.ClearProviders(); logging.AddConsole(); }) .ConfigureWebHostDefaults(webBuilder =>{ webBuilder.UseStartup<Startup>(); });
You can create logs using the ILogger interface, which is injected into your code by the ASP.NET Core dependency injection container. The following example illustrates this.
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace Razor.Pages{ public class IndexModel : PageModel{ private readonly ILogger<IndexModel> _logger; public IndexModel(ILogger<IndexModel> logger){ _logger = logger; } public void OnGet(){ _logger.LogInformation("Index page visited."); } } }
In a production application, logging is critical for swiftly diagnosing, debugging, and fixing faults. Configuring logging as soon as possible, ideally when you begin designing your application, is a best practice.