ASP.NET:How to write error messages into a text file using a simple httpModule

In one of my previous posts, I mentioned about how to troubleshoot some issues with the use of a module. In this post, I will show you how a similar module could be of use when you want to log all the errors in a text file for troubleshooting purposes. Please ensure that C:\Temp folder has Write access for the account that is running the IIS Worker Process. Here is the code for the module...

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.IO;
namespace myModules
class Trigger:IHttpModule
public void Init(System.Web.HttpApplication context)
context.EndRequest += new EventHandler(this.EndRoutine);
public void EndRoutine(object o, EventArgs e)
HttpApplication myApp;
myApp = (HttpApplication)o;
HttpContext c = myApp.Context;
if (myApp.Context.AllErrors != null)
StreamWriter sw = new StreamWriter("C:\\Temp\\ErrorList.txt", true);
foreach (Exception ex in myApp.Context.AllErrors)
sw.WriteLine("Error occurred at #{0}", DateTime.Now.ToString());
sw.WriteLine("Error occurred in page #{0}", c.Request.FilePath);
public void Dispose()
//Nothing to Dispose as of now

You can save the downloaded file to the bin folder of your web application and add the following to the web.config...

add name="Trigger" type="myModules.Trigger, myModules"/>

Here is the sample output (C:\Temp\ErrorList.txt) for one of the applications where I have used the Throw New AppDomainUnloadedException or similar lines to create the error...


Hope this helps, Happy

Quote of the day:
The nice thing about standards is that there are so many of them to choose from. - Andrew S. Tanenbaum

Posted at > 6:10 PM IST

Skip to main content