Section 1 of 6
ILogger Interface
🎯 What You'll Learn
- What is logging
- ILogger interface
- Dependency injection
- Basic logging methods
- InvenTrack examples
What is Logging?
Logging records events that happen in your application. It helps with debugging, monitoring, and understanding application behavior.
ILogger Interface
ASP.NET Core provides the ILogger<T> interface for logging.
Dependency Injection
Inject ILogger
C#
public class ProductsController : Controller
{
private readonly ILogger<ProductsController> _logger;
public ProductsController(ILogger<ProductsController> logger)
{
_logger = logger;
}
}
Basic Logging Methods
Log Methods
C#
_logger.LogTrace("Trace message");
_logger.LogDebug("Debug message");
_logger.LogInformation("Information message");
_logger.LogWarning("Warning message");
_logger.LogError("Error message");
_logger.LogCritical("Critical message");
Logging with Parameters
Structured Logging
C#
_logger.LogInformation("Product {ProductId} created by {UserId}", productId, userId);
Logging Exceptions
Log Exception
C#
try
{
// Some operation
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to create product {ProductId}", productId);
}
InvenTrack Example
ProductsController.cs
C#
public class ProductsController : Controller
{
private readonly ILogger<ProductsController> _logger;
private readonly InvenTrackDbContext _context;
[HttpPost]
public async Task<IActionResult> Create(Product product)
{
_logger.LogInformation("Creating product {ProductName}", product.Name);
try
{
_context.Products.Add(product);
await _context.SaveChangesAsync();
_logger.LogInformation("Product {ProductId} created successfully", product.Id);
return RedirectToAction("Index");
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to create product {ProductName}", product.Name);
return View(product);
}
}
}
Key Takeaways
- ILogger<T>: Logging interface
- Dependency injection: Inject ILogger in constructor
- Log methods: LogTrace, LogDebug, LogInformation, LogWarning, LogError, LogCritical
- Parameters: Use placeholders {Name} for structured logging
- Exceptions: Pass exception as first parameter