ASP.NET Core has built in support for logging and allows developers to easily leverage their preferred logging framework as well.
The logging service works with logging providers that store or display logs to a particular medium such as console, debug, trace listeners. For eg : The console provider displays the logs on the console and azure application insightt provider stores them in azure application insights, similarly we have many more providers like Nlog etc.
Now to simply log into your console.
Step 1 : Add a provider, i.e. console in your case.
In your program.cs after the main method paste this
public static void Main(string[] args)
{
var host = CreateWebHostBuilder(args).Build();
var todoRepository = host.Services.GetRequiredService<ITodoRepository>();
todoRepository.Add(new Core.Model.TodoItem() { Name = "Feed the dog" });
todoRepository.Add(new Core.Model.TodoItem() { Name = "Walk the dog" });
var logger = host.Services.GetRequiredService<ILogger<Program>>();
logger.LogInformation("Seeded the database.");
host.Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.AddConsole(); \\adding to console
});
Step 2 :Then inject the ILogger in your class through constructor
public class AboutModel
{
private readonly ILogger _logger;
public AboutModel(ILogger<AboutModel> logger)
{
_logger = logger;
}
}
Step 3 : And then just mention the type of log you want to save and give its message.
public void OnGet()
{
Message = $"About page visited at {DateTime.UtcNow.ToLongTimeString()}";
_logger.LogInformation("Message displayed: {Message}", Message);
}
In the above method we are using information level log which specifies that program ends correctly.
Hope this helps.