Error Handling and Logging in ASP.NET Core Applications
๐จ Error Handling and Logging in ASP.NET Core Applications
Building robust ASP.NET Core applications requires proper error handling and logging to detect, diagnose, and recover from issues efficiently.
1. Error Handling in ASP.NET Core
Built-in Middleware for Error Handling
Developer Exception Page
Shows detailed error information, useful during development.
csharp
Copy
Edit
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
Exception Handling Middleware
For production, use a generic error handler to avoid exposing sensitive info:
csharp
Copy
Edit
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
Custom Error Pages
You can create custom error pages (e.g., 404, 500) to improve user experience.
Handling Exceptions in Code
Use try-catch blocks to catch expected exceptions.
Throw custom exceptions for specific error cases.
Use middleware or filters to handle unhandled exceptions globally.
2. Logging in ASP.NET Core
ASP.NET Core has built-in logging abstractions with support for multiple providers.
Common Logging Providers
Console
Debug
EventSource
Files (via third-party libraries like Serilog, NLog)
Application Insights
Configuring Logging
Example in Program.cs or Startup.cs:
csharp
Copy
Edit
public void Configure(IApplicationBuilder app, ILogger<Startup> logger)
{
logger.LogInformation("Application started.");
// other middleware
}
Using the Logger in Controllers or Services
csharp
Copy
Edit
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
_logger.LogInformation("Index page visited.");
try
{
// some code that might fail
}
catch (Exception ex)
{
_logger.LogError(ex, "Error occurred while processing Index.");
// handle exception or return error view
}
return View();
}
}
3. Best Practices
Centralize error handling using middleware or filters.
Log exceptions with stack traces for easier debugging.
Avoid logging sensitive data.
Use structured logging (key-value pairs) for better querying.
Configure different log levels (Information, Warning, Error) depending on environment.
Monitor logs regularly to identify and fix issues proactively.
4. Advanced: Using Third-Party Logging Frameworks
Popular frameworks like Serilog or NLog provide:
File logging
Rolling logs
Rich formatting
Integration with various sinks (databases, cloud services)
Example: Adding Serilog
csharp
Copy
Edit
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.WriteTo.File("logs/log-.txt", rollingInterval: RollingInterval.Day)
.CreateLogger();
hostBuilder.UseSerilog();
Summary
Aspect Description
Error Handling Use middleware for global handling and custom error pages. Catch exceptions where necessary.
Logging Use built-in ILogger abstraction with providers. Log key events and errors.
Best Practices Centralize error handling, log relevant info without sensitive data, and use structured logs.
Learn Full Stack Dot NET Training in Hyderabad
Read More
Implementing Authentication and Authorization in .NET Core Apps
How to Use Entity Framework Core for Database Management in Full Stack .NET
Visit Our Quality Thought Training in Hyderabad
Comments
Post a Comment