Logging is a critical part of any application for monitoring, debugging, and troubleshooting. ASP.NET Core comes with a flexible and powerful built-in logging framework that allows you to plug in various logging providers to send logs to different destinations.
In this article, you'll learn about the built-in logging providers in ASP.NET Core, how they work, and when to use each one.
What Is a Logging Provider?
A logging provider is a component that processes and stores log messages. ASP.NET Core allows you to configure one or more providers that can write logs to:
- Console
- Debug window
- Event log (Windows)
- Files
- External systems (like Seq, ELK, or Application Insights)
You can configure logging providers in Program.cs:
var builder = WebApplication.CreateBuilder(args); // Add built-in providers builder.Logging.ClearProviders(); // Optional: clears default providers builder.Logging.AddConsole(); builder.Logging.AddDebug(); builder.Logging.AddEventSourceLogger(); var app = builder.Build();
"Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }
What is ILogger?
ILogger<T> is ASP.NET Core’s built-in logging interface that allows you to log messages inside your classes (controllers, services, etc.).
It supports:
- Different log levels (Information, Warning, Error, etc.)
- Structured logging (log message + key-value pairs)
- Logging to multiple providers (console, file, debug, etc.)
How to Use ILogger in ASP.NET Core
Step 1: Inject ILogger<T> in the Constructor.
public class ProductService { private readonly ILogger<ProductService> _logger; public ProductService(ILogger<ProductService> logger) { _logger = logger; } public void GetProduct() { _logger.LogInformation("Fetching product..."); } }
Step 2: Register and Use the Service in the Controller.
[ApiController] [Route("api/[controller]")] public class ProductController : ControllerBase { private readonly ProductService _service; public ProductController(ProductService service) { _service = service; } [HttpGet] public IActionResult Get() { _service.GetProduct(); return Ok("Product fetched."); } }
You can log at different severity levels:
_logger.LogTrace("Trace log"); _logger.LogDebug("Debugging info"); _logger.LogInformation("General info"); _logger.LogWarning("Something might be wrong"); _logger.LogError("An error occurred"); _logger.LogCritical("Critical issue!");
Complete Example:
[ApiController] [Route("api/[controller]")] public class OrderController : ControllerBase { private readonly ILogger<OrderController> _logger; public OrderController(ILogger<OrderController> logger) { _logger = logger; } [HttpGet("{id}")] public IActionResult GetOrder(int id) { _logger.LogInformation("Fetching order with ID {OrderId}", id); if (id <= 0) { _logger.LogWarning("Invalid order ID: {OrderId}", id); return BadRequest("Invalid ID"); } return Ok($"Order #{id}"); } }
How To Use Serilog in ASP.NET Core?
Serilog is a powerful logging library for .NET that supports structured logging, file output, sinks like Seq, and is easy to plug into ASP.NET Core.
Here’s a step-by-step example of using Serilog in an ASP.NET Core Web API project:
Step 1: Install Serilog NuGet Packages
Run these commands in your terminal:
dotnet add package Serilog.AspNetCore dotnet add package Serilog.Sinks.Console dotnet add package Serilog.Sinks.File
Update your Program.cs to use Serilog before building the host:
using Serilog; var builder = WebApplication.CreateBuilder(args); // 🔹 Configure Serilog before building the app Log.Logger = new LoggerConfiguration() .MinimumLevel.Information() .WriteTo.Console() .WriteTo.File("Logs/log-.txt", rollingInterval: RollingInterval.Day) .Enrich.FromLogContext() .CreateLogger(); // Replace default logger with Serilog builder.Host.UseSerilog(); builder.Services.AddControllers(); var app = builder.Build(); app.UseAuthorization(); app.MapControllers(); app.Run();
Serilog integrates with ILogger<T> automatically. No need to use Serilog types directly.
[ApiController] [Route("api/[controller]")] public class TestController : ControllerBase { private readonly ILogger<TestController> _logger; public TestController(ILogger<TestController> logger) { _logger = logger; } [HttpGet("{id}")] public IActionResult Get(int id) { _logger.LogInformation("Request received for ID: {Id}", id); if (id <= 0) { _logger.LogWarning("Invalid ID: {Id}", id); return BadRequest("Invalid ID"); } return Ok($"Item #{id}"); } }
[10:30:12 INF] Request received for ID: 5 [10:30:14 WRN] Invalid ID: -1
No comments:
Post a Comment