Skip to main content

ASP.NET Core - Log exceptions to the IIS log


This is only applicable when you are NOT using MVC in your application


1. Required Packages : 

  • Microsoft.Extensions.Logging
  • Microsoft.Extensions.Logging.Console


2. Middleware for Exception Login : 

public class ExceptionLoggingMiddleware  
 {  
   private readonly RequestDelegate _next;  
   private readonly ILogger<ExceptionLoggingMiddleware> _logger;  
   public ExceptionLoggingMiddleware(RequestDelegate next, ILogger<ExceptionLoggingMiddleware> logger)  
   {  
     _next = next;  
     _logger = logger;  
   }  
   public async Task InvokeAsync(HttpContext context)  
   {  
     try  
     {  
       await _next(context);  
     }  
     catch (Exception ex)  
     {  
       _logger.LogError(ex, "An unhandled exception occurred.");  
       throw; // Rethrow the exception after logging it  
     }  
   }  
 }  


3. Configure your Program.cs

 using Microsoft.AspNetCore.Builder;  
 using Microsoft.AspNetCore.Hosting;  
 using Microsoft.Extensions.DependencyInjection;  
 using Microsoft.Extensions.Hosting;  
 using Microsoft.Extensions.Logging;  
 var builder = WebApplication.CreateBuilder(args);  
 // Configure logging  
 builder.Logging.ClearProviders();  
 builder.Logging.AddConsole();  
 builder.Logging.AddFile("Logs/app-{Date}.log");   
 var app = builder.Build();  
 // Add custom middleware for exception logging  
 app.UseMiddleware<ExceptionLoggingMiddleware>();  
 // Define endpoints  
 app.MapGet("/", () => "Hello World!");  
 app.Run();  
 public class ExceptionLoggingMiddleware  
 {  
   private readonly RequestDelegate _next;  
   private readonly ILogger<ExceptionLoggingMiddleware> _logger;  
   public ExceptionLoggingMiddleware(RequestDelegate next, ILogger<ExceptionLoggingMiddleware> logger)  
   {  
     _next = next;  
     _logger = logger;  
   }  
   public async Task InvokeAsync(HttpContext context)  
   {  
     try  
     {  
       await _next(context);  
     }  
     catch (Exception ex)  
     {  
       _logger.LogError(ex, "An unhandled exception occurred.");  
       throw; // Rethrow the exception after logging it  
     }  
   }  
 }  


4.  Set Up File Permissions for IIS

  • Create a Logs directory in your application root
  • Right-click the Logs folder in Windows Explorer.
  • Go to Properties.
  • Navigate to the Security tab.
  • Click Edit, then Add, and enter IIS_IUSRS.
  • Grant Write permissions to the IIS_IUSRS user.

Comments

Popular posts from this blog

Limitations of If Else Statements in ServiceNow Flow Designer

The ServiceNow Flow Designer is a powerful tool for automating workflows and processes. However, the If Else statement within the Flow Designer has certain limitations that users must be aware of, particularly when it comes to complex conditions, nesting, performance, debugging, user interface, maintenance, and scalability. Complex Conditions A significant limitation of the If Else statement in ServiceNow Flow Designer is its handling of complex logical operators. The Flow Designer supports basic conditions, but it may not handle operators like AND, OR, and NOT as intuitively as some other platforms. Combining multiple conditions can sometimes become cumbersome, making it challenging to implement sophisticated business logic effectively. Nested If Else Statements While it is possible to nest If Else statements within the Flow Designer, there is a practical limit to how deeply they can be nested. Excessive nesting can lead to a cluttered and hard-to-read flow, making it difficult to man...

Strategically Positioning ServiceNow in Your Organizational Roadmap

Here’s how you can strategically position ServiceNow in your organizational roadmap. 1. Assessment and Alignment with Business Goals Step 1: Comprehensive Needs Assessment Begin by conducting a thorough assessment of your organization’s current processes, pain points, and future aspirations. Identify the areas where automation and improved workflows can have the most impact. Step 2: Align with Business Objectives Align these findings with your overarching business goals. Whether it’s improving customer satisfaction, enhancing employee productivity, or ensuring better compliance and risk management, understanding how ServiceNow can support these objectives is crucial. 2. Building a Cross-Functional Team Step 1: Engage Stakeholders Form a cross-functional team that includes representatives from IT, HR, finance, and other critical departments. Their insights will be invaluable in understanding the unique needs and challenges of each department. Step 2: Define Roles and Responsibilities Cl...

ServiceNow, ITIL and Agile - A different symphony

As a 9+ experienced Solution Architect who is mainly focusing on software system automation in ITSM Domain, I had the invaluable opportunity of being a part of a few successful business transitioning projects. With that experience on hand, I'm writing this article to share the challenges you can expect during this kind of transition. Agile Since we are in a rapidly changing business world which directly depends on IT, IT organizations play major roles in every business. Bigger the company, the responsibility of the IT company getting bigger and bigger day by day. Things get much more complicated when an IT organization supports IT businesses like Software development firms or Infrastructure services providers. Therefore a better process of managing delivery activities is required for such an IT company.  Many years ago, When Agile invaded the tech market, businesses eagerly looked forward to restructuring their IT organizations according to those practices.  Agile is a pr...