Introduction
Logging is one of the most important parts of any modern web application. Whether you are building a small API or a large enterprise system in ASP.NET Core, logging helps you understand what is happening inside your application.
In simple words, logging means:
π Recording important information about your application while it is running.
Using logging, you can:
ASP.NET Core provides a powerful built-in logging system using ILogger, which is easy to use and highly flexible.
In this detailed guide, you will learn how to implement logging in ASP.NET Core using ILogger in a simple and practical way.
What is ILogger in ASP.NET Core?
Understanding ILogger in Simple Words
ILogger is a built-in interface in ASP.NET Core that helps developers log messages from their applications.
It supports multiple logging providers like:
π The best part is that it is already configured by default in ASP.NET Core.
Why Logging is Important in ASP.NET Core Applications
Logging is essential for building reliable and production-ready applications.
Hereβs why:
Helps identify and fix bugs quickly
Provides insights into application flow
Helps monitor API requests and responses
Useful for debugging production issues
Logging Levels in ASP.NET Core
ASP.NET Core provides different logging levels to categorize logs.
Common Logging Levels
Trace β Detailed information (rarely used in production)
Debug β Useful during development
Information β General application flow
Warning β Something unexpected but not critical
Error β Something failed
Critical β Application crash or serious issue
π Choosing the correct logging level is very important for effective logging.
How to Use ILogger in ASP.NET Core
Letβs now implement logging step by step.
Inject ILogger into Controller
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
}
π ILogger is injected using Dependency Injection.
Write Log Messages
_logger.LogInformation("This is an information log");
_logger.LogWarning("This is a warning log");
_logger.LogError("This is an error log");
π You can log messages based on severity level.
Logging in ASP.NET Core Web API Example
Example API with Logging
[ApiController]
[Route("api/[controller]")]
public class UserController : ControllerBase
{
private readonly ILogger<UserController> _logger;
public UserController(ILogger<UserController> logger)
{
_logger = logger;
}
[HttpGet("{id}")]
public IActionResult GetUser(int id)
{
_logger.LogInformation($"Fetching user with ID: {id}");
if (id <= 0)
{
_logger.LogWarning("Invalid user ID provided");
return BadRequest("Invalid ID");
}
try
{
// Simulated logic
var user = new { Id = id, Name = "John" };
_logger.LogInformation("User fetched successfully");
return Ok(user);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error occurred while fetching user");
return StatusCode(500, "Internal server error");
}
}
}
π This example shows how logging helps track the flow of API execution.
Configure Logging in appsettings.json
You can control logging behavior using configuration.
Example Configuration
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}
What This Means
π This helps reduce unnecessary logs in production.
Logging to Console and Debug Window
By default, ASP.NET Core logs to:
π You donβt need extra setup for basic logging.
Structured Logging in ASP.NET Core
Structured logging helps you log data in a readable and searchable format.
Example
_logger.LogInformation("User {UserId} logged in at {Time}", userId, DateTime.Now);
π This makes logs easier to analyze in tools like Kibana or Seq.
Best Practices for Logging in ASP.NET Core
Use Appropriate Log Levels
Do not log everything as Error. Use levels wisely.
Avoid Logging Sensitive Data
Never log passwords, tokens, or personal data.
Use Structured Logging
It improves readability and searchability.
Keep Logs Clean and Meaningful
Write clear messages that help debugging.
Enable Logging in Production Carefully
Too many logs can impact performance.
Common Mistakes to Avoid
Logging Too Much Information
Too many logs can make it hard to find real issues.
Not Handling Exceptions Properly
Always log exceptions with details.
Ignoring Log Configuration
Proper configuration is important for production environments.
Summary
Logging in ASP.NET Core using ILogger is simple, powerful, and essential for building reliable applications. It helps developers track application behavior, debug issues, and monitor performance effectively. By understanding logging levels, using dependency injection, writing meaningful log messages, and following best practices, you can implement a robust logging system in your ASP.NET Core Web API or MVC application. Proper logging ensures better debugging, smoother production monitoring, and improved application quality.