Roadmap › Logging & Custom Logging in .NET — ILogger, Serilog, NLog, log4net and Your Own Logger › Module: Logging Fundamentals
Lessons in this course (8)
2. Microsoft.Extensions.Logging — ILogger, providers and configuration
Basic★ Must knowLesson 2 of 8
csharp
public class OrderService(ILogger<OrderService> logger) // category = full class name
{
public async Task PlaceAsync(Order order)
{
logger.LogInformation("Placing order {OrderId} with {LineCount} lines", order.Id, order.Lines.Count);
try
{
await repository.SaveAsync(order);
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to save order {OrderId}", order.Id); // exception first parameter
throw;
}
}
}Providers (where logs go): Console, Debug, EventSource, EventLog (Windows), Azure App Service, Application Insights, OpenTelemetry — plus third-party (Serilog, NLog) plugged in as providers.
csharp
var builder = WebApplication.CreateBuilder(args); // adds Console, Debug, EventSource (+ EventLog on Windows) by default
builder.Logging.ClearProviders();
builder.Logging.AddConsole();
builder.Logging.AddJsonConsole(); // structured JSON to stdout — ideal for containersFiltering by category and level (appsettings.json):
json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"Microsoft.EntityFrameworkCore.Database.Command": "Warning",
"Divakar.Shop.Payments": "Debug"
},
"Console": { "LogLevel": { "Default": "Warning" } }
}
}The most specific category prefix wins; provider-specific sections override the general one; appsettings.Development.json usually turns on Debug.