Logging Errors to the Event Log in ASP.NET Applications

Let's face it. We're not living in a perfect world. I am not a perfect programmer, and the same probably applies to you (otherwise you would be stinkin' rich, laying on the beach somewhere drinking a Bacardi and Coke, instead of reading this article).

Because we aren't perfect, we know we are going to run into errors in the applications we write sooner or later. This article will explain how you can catch these errors in your ASP.NET applications and log them to the Windows Event log, so it's easy to review them later. The article focuses on ASP.NET, but the principle applies to other .NET applications as well.

Prerequisites

In this article, I am going to use Visual Studio .NET 2003, so it's handy if you have that to your availability. Visual Studio .NET 2002 will do as well, and you can even follow along if you program in Notepad and use the command line compilers.

I'll be using C# as the main language, but you could easily write the code in Visual Basic .NET.

Errors? What Errors? I compiled the application and it looks fine!

With the arrival of IDEs like Visual Studio .NET and smart compilers, you can catch quite a lot of errors at design time. Syntax errors, undeclared variables, unsafe casts etc can all be caught by the compiler. So, some people believe that if they compile without getting an error or a warning from the compiler, their application is good and bug-free. Unfortunately, this is not true. Even though the program is free of syntax errors, you can still run into design mistakes or run-time errors. Important files could be missing, required fields are not filled in correctly, people break the interface of a public Web Service you were using and so on. These are all examples of errors that you cannot handle at design-time. You must handle them at run-time.

If these errors occur, you have to be sure that you get detailed information about them. Your user should never be bothered with detailed error information about call stacks and other scary technical jargon. Instead, you should present them with a friendly error message that explains in plain English what went wrong and that you were notified about the error and are now working very hard to fix it. You could also offer them an alternative to continue browsing your site, by providing them a link back to your home page for example. To find out how you can configure your application, be sure to read this article. It explains how to modify the Web.Config file and your Global class to catch errors and send an e-mail to the administrator of the site, informing him or her about the error, accompanied by a detailed error message.

We Want More!

Sending an e-mail is good because it will alert the right people right after the error occurred. However, e-mails tend to get lost, or popped at the wrong computer so you can't access them from your development machine, or the ones who received the e-mail aren't responsible for fixing the error.

So what would be another logical place to log the error? Right on the server where the error occurred, in the Windows Event log. Writing to the event log used to be problematic, but the .NET Framework has a few handy classes available that make writing to the log a breeze. In the remainder of this article I will demonstrate how you can catch your errors and log them to the Windows Event Log.

First Things First

With early beta releases of the ASP.NET Framework, it was possible to create new Events Logs (besides Application, Security and System) and Event Sources at run-time. That was because ASP.NET was running under the System account which had full privileges, including writing to the registry, which is necessary to create Event Logs and Sources. However, with the final releases of the .NET Framework (1.0 and 1.1), this is no longer possible. One way to fix this problem is to give the required permissions to the ASPNET account. However, this is not very recommended. The ASPNET account is a least privileged account, and for security reasons, it's best to leave it that way. Besides, you do not really need to create the logs at run-time, as they are not likely to change that often. So, it's best to create the Event Log and Source at design or deployment time. The easiest way to do this is to use a Windows Forms application. It's easy to run such an application with administrative privileges (using Run As for example), so you can easily bypass the security restrictions.

Before I show you how to create this application, let's take a look first at what the Event Log and the Event Source are. If you know all about the Event Log and just want to know how to create your own, go ahead and skip to the section Creating Your Own Event Log.

The Event Log

The Event Logs on your computer are accessible through the Event Viewer which you can find under the Administrative Tools menu. On a normal installation, you have three default Event Logs: Application, Security and System. The Application log is used to record information from applications. If you take a look in the Application log, you'll see logs from applications you're probably familiar with, like Office installations, SQL Server, backup programs and so on.
The Security log is not used much by default; however you can enable thorough access logging so more details about user sign-ons, access checks etc are logged.
The System log is used to log events from Windows components, like driver or service failures.
If you look at these three logs, you probably think that the Application log is best for logging your custom errors. That's true, but there is even a better solution: the custom Event Log. I'll get to that in a bit.

The Event Source

The Event Source is usually the name of the application that logged the event, but this is not required. In this article, however, I'll stick to this recommendation and use the full address of my Web site as the name of the Event Source. This allows me to easily distinguish errors I am interested in from errors from other sources. Feel free to choose a different naming convention, though.

The following screen shot shows you the Event Viewer. You can see the custom Event Log, My Websites, in the right-hand pane and you can see that the events are logged under the source Imar.Spaanjaars.com, the name of the Web site that generated the event.

The Event Viewer with the Custom Event Log visible
Figure 1 - The Event Viewer with the Custom Event Log visible

Creating Your Own Event Log

It's remarkably simple to create a new Event Log. All you need to do is call the static CreateEventSource method of the EventLog class that lives in the System.Diagnostics namespace. So, fire up Visual Studio .NET to create the application that will create the Event Log and Source. (The source code for this article includes the full source of the application, in case you want to try it out directly.)

  1. Once you started Visual Studio, create a new Visual C# Windows Application. Name the application CreateEventLog.

  2. Drag two labels, two textboxes and a button from the Toolbox to the form and set their properties as follows:

    Control (Name) Text
    Label 1 lblEventLog Event Log
    Label 2 lblEventSource Event Source
    Textbox 1 txtEventLog  
    Textbox 2 txtEventSource  
    Button 1 btnCreateEventLog Create Event Log

    Arrange the controls so they end up as in the following screen shot:

    The Sample Application
    Figure 2 - The Sample Application

  3. Double click the button, and add the following code for the btnCreateEventLog_Click handler:

    private void btnCreateEventLog_Click(object sender, System.EventArgs e)
    {
      if (txtEventLog.Text.Length > 0 && txtEventSource.Text.Length > 0)
      {
        System.Diagnostics.EventLog.CreateEventSource(
    txtEventSource.Text, txtEventLog.Text);
    MessageBox.Show("Event Log and Source " +
    "created successfully.");
    } else { MessageBox.Show("Please fill in both the " +
    "Event Log and the Event Source.");
    }
    }
    This code will check if both required fields are filled in, and if they are create the requested Event Log and Event Source.

  4. Press F5 to start the application, type My Websites for the Event Log name and the URL of your site, like www.MySite.com as the Event Source and click the Create Event Log button.

  5. Open up the Event Viewer (close it first if you had it still open to refresh its contents) and you'll see your new Event Log as in the first screen shot of this article.
    That was easy, wasn't it?

Writing to the Event Log

Creating a new Event Log and Source is easy, but writing to it is about as easy.

  1. First of all, make sure you followed the steps from the article How do I Handle Errors and Send an Error Notification from ASP.NET Applications? Make sure you changed at least the Web.Config file so it includes the customErrors node with its mode set to On:
    <customErrors mode="On">
    	<error statusCode="500" redirect="/InternalError.htm"/>
    </customErrors>
    The InternalError.htm page is the page your users will see when an error occurs and generally contains a user-friendly explanation that an error has occurred.

  2. Next, open the Web application that you want to log errors for and open the Code Behind page for the Global class (Global.asax.cs, or Global.asax.vb if you're using VB.NET).

  3. Add the following using statement to the top of the Code Behind page:
    using System.Diagnostics;
  4. Add the following code to the Application_Error event. (If you followed along with the previous article, and added code that e-mailed you the detailed error information, add the following code below the code already present for the event):
    protected void Application_Error(Object sender, EventArgs e)
    {
      // Log error to the Event Log
      Exception myError = null;
      if (HttpContext.Current.Server.GetLastError() != null)
      {
        string eventLog = "My Websites";
        string eventSource = "www.MySite.Com";
        string myErrorMessage = "";
    
        myError = Server.GetLastError();
    
    while (myError.InnerException != null) { myErrorMessage += "Message\r\n" + myError.Message.ToString() + "\r\n\r\n"; myErrorMessage += "Source\r\n" + myError.Source + "\r\n\r\n"; myErrorMessage += "Target site\r\n" + myError.TargetSite.ToString() + "\r\n\r\n"; myErrorMessage += "Stack trace\r\n" + myError.StackTrace + "\r\n\r\n"; myErrorMessage += "ToString()\r\n\r\n" + myError.ToString(); // Assign the next InnerException // to catch the details of that exception as well myError = myError.InnerException; } // Make sure the Eventlog Exists if(EventLog.SourceExists(eventSource)) { // Create an EventLog instance and assign its source. EventLog myLog = new EventLog(eventLog); myLog.Source = eventSource; // Write the error entry to the event log. myLog.WriteEntry("An error occurred in the Web application "
    + eventSource + "\r\n\r\n" + myErrorMessage, EventLogEntryType.Error);
    } }
    }

    Don't forget to replace the parts in bold with the names you have chosen for your Event Log and Source.

  5. To test out the new logging feature of your site, add a new Web Form to your application and call it TestLogging.aspx.

  6. Open the Code Behind for the page, and add the following code that will explicitly generate an error to the Page_Load event:

    private void Page_Load(object sender, System.EventArgs e)
    {
      throw new Exception("An error occurred in the " +
    "Page_Load of the TestLogging page.");
    }
  7. Save the page, compile your application and then open TestLogging.aspx in your browser. Instead of the usual error page, you should see your custom error page you defined in step 1.

  8. Start the Event Viewer and open your custom Event Log. You should see a new event log entry with the details of the error that occurred. Double-click the event log entry to see the dirty details of your error:

    The Event Properties dialog displays the detailed error message.
    Figure 3 - The Event Properties Dialog Displays the Detailed Error Nessage.

For this little example, I explicitly threw a new error using the throw keyword. However, the logging mechanism I showed you will catch all errors that may occur in your code, including any unhandled exceptions. This will help tremendously in pinpointing and fixing the problem.

Notice that the code in the Application_Errorevent uses a loop to retrieve information about the InnerException. If you don't use the loop, you'll end up with a rather meaningless "System.Web.HttpUnhandledException" message, without all the nitty gritty details about your error.

Also, sometimes explicitly nested errors are created, by passing in a Exception (the Inner Exception) to the constructor of another Exception (the Outer Exception) before the Outer Exception is thrown. This allows programmers to add useful information about the error, while leaving the original error and message in tact.

Instead of looping through the exceptions, you can also call GetBaseException() to get at the inner most exception directly:

myError = Server.GetLastError().GetBaseException();
	
myErrorMessage += "Message\r\n" +
	myError.Message.ToString() + "\r\n\r\n";
myErrorMessage += "Source\r\n" +
	myError.Source + "\r\n\r\n";
myErrorMessage += "Target site\r\n" +
	myError.TargetSite.ToString() + "\r\n\r\n";
myErrorMessage += "Stack trace\r\n" +
	myError.StackTrace + "\r\n\r\n";
myErrorMessage += "ToString()\r\n\r\n" +
	myError.ToString();  

What's Next

The purpose of this article is to show you the general idea of logging to the Event Log. It's by no means a complete solution (although you can use the code directly to enable logging in relatively small applications). Here are some ideas to extend the concepts that were introduced in this article:

  • Create a class ExceptionLogger with a few overloaded methods like LogError. Have the methods accept various flavors of exceptions, exception messages and EventLogEntryTypes (Error, Warning, Information and so on) and log the errors to the Event log. This allows you to log errors or other events to the Event log from within a Catch block, without interrupting the page flow and relying on the global exception handler.
  • Add backup code that logs the errors to a text file or sends out an e-mail in case the Event Log or Source does not exist. This shouldn't happen because you created the Logs and Source yourself at installation time, but, hey, it's not a perfect world.
  • Create different Event Sources for your application. This allows you to make a distinction between different kind of event log entries so it's easier to locate the important ones.

There is Even More

Much of what I have introduced in this article, has already been taken care of by Microsoft. In April 2002, Microsoft released the Exception Management Application Block for .NET, a complete solution including full source code for publishing your errors to different logs, including the Event Log, SQL Server and a custom log that you define (an XML / text file or a pager or mobile phone for example).

The Application Block may be a bit overwhelming at first, and difficult to install and configure if you don't read the documentation carefully. It's not always necessary or applicable to use the Exception Management Application Block. For smaller sites or applications, the logging I demonstrated in this article should be more than enough.

Additionally, you can take a look at ELMAH (Error Logging Modules & Handlers), an open source project that allows you to send exception messages by e-mail or store them in a database. It's easy to setup and can also be implemented in existing solutions without the need to recompile anything. You can check out the project on its GotDotNet workspace.

References

Download Files

Source Code for this Article (Includes the Windows Application and two test web sites voor ASP.NET 1.x and ASP.NET 2.0)

Where to Next?

Wonder where to go next? You can read existing comments below or you can post a comment yourself on this article .


Consider making a donation
Please consider making a donation using PayPal. Your donation helps me to pay the bills so I can keep running Imar.Spaanjaars.Com, providing fresh content as often as possible.



Feedback by Other Visitors of Imar.Spaanjaars.Com

On Sunday, December 05, 2004 2:06:29 PM avichai kalij said:
Hi ,

what if i have a sturcture like this :

/wwwroot
    /app1
    /app2

can i create an aspx page (with inline code because wwwroot is not application) so it will handle it for both of app1 and app2.I tried it but HttpContext.Current.Server.GetLastError return null when i am using it from that aspx page.
What am i missing?
Is it because it has to be application (wwwroot)?
On Sunday, December 05, 2004 2:58:37 PM Imar Spaanjaars said:
Correct. Application_Error is tied to the current application that is causing the error. That means that Application_Error will fire for each web application so each application also needs its own Global.asax with Application_Error to handle the errors.
On Sunday, March 06, 2005 1:37:28 PM avichai kalij said:
hi ,
i have the same structure :

/wwwroot
    /app1
    /app2

My problem is that app1 and app2 are both applications and the wwwroot
but when i thorw error from app1 or app2 the  HttpContext.Current.Server.GetLastError returns null.
what am i missing ?
On Sunday, March 06, 2005 1:41:53 PM Imar Spaanjaars said:
In what page /class and method are you using HttpContext.Current.Server.GetLastError??
On Tuesday, May 23, 2006 3:12:28 PM mohamed hassan said:
thnaks
On Thursday, December 14, 2006 11:31:06 AM vinaykeshav said:
Thanks for such a good article of handing event.

Imagine a situation where we would have written code at global.ascx.cs
and accidently the web.dll gets deleted and at the web.config even the
redirection happens to error page it will not log error at event log.
Is there any method to fix this issue and make the event log generated..

Please mail me your thoughts for the same.
On Thursday, December 14, 2006 9:33:38 PM Imar Spaanjaars said:
Hi vinaykeshav,

In .NET 2 you can write code directly in the Global.asax file to handle these events. However, if that file is deleted you're still out of luck.

Take a look at Elmah that can handle a lot of these issues for you (as long as you don't delete its DLL and the web.config file).

Personally, I'd spend some time instructing people not to delete crucial files from a productiion server, but hey, that's just me ;-)

Cheers,

Imar
On Friday, December 15, 2006 6:18:28 AM vinaykeshav said:
thanks Imar for looking at the comment.
On Tuesday, February 06, 2007 5:19:40 AM Roshan said:
I have a server and the web application is running from that is copy and paste the above code and change

string eventLog = "My Websites";
string eventSource = "www.MySite.Com";

but the Error is not wrriten to the event Viewer.

what should i do ??
On Tuesday, February 06, 2007 6:29:10 AM Imar Spaanjaars said:
Hi Roshan,

Did you run the sample application and create the event log?

Imar
On Tuesday, February 06, 2007 12:55:45 PM Roshan said:
Ya i did i debug the code as well, i got no error but it is not written to the event viewer

Following is the code i written:


protected void Application_Error(Object sender, EventArgs e)
{

// Log error to the Event Log
Exception myError = null;
if (HttpContext.Current.Server.GetLastError() != null)
{
string eventLog = "Mailbag Media";
string eventSource = "http://braintech/mbm";
string myErrorMessage = "";

myError = Server.GetLastError();

while (myError.InnerException != null)
{
myErrorMessage += "Message\r\n" +
myError.Message.ToString() + "\r\n\r\n";
myErrorMessage += "Source\r\n" +
myError.Source + "\r\n\r\n";
myErrorMessage += "Target site\r\n" +
myError.TargetSite.ToString() + "\r\n\r\n";
myErrorMessage += "Stack trace\r\n" +
myError.StackTrace + "\r\n\r\n";
myErrorMessage += "ToString()\r\n\r\n" +
myError.ToString();

// Assign the next InnerException
// to catch the details of that exception as well
myError = myError.InnerException;
}

// Make sure the Eventlog Exists
if(EventLog.SourceExists(eventSource))
{
// Create an EventLog instance and assign its source.
EventLog myLog = new EventLog(eventLog);
myLog.Source = eventSource;
    
// Write the error entry to the event log.    
myLog.WriteEntry("An error occurred in the Web application "
+ eventSource + "\r\n\r\n" + myErrorMessage,
EventLogEntryType.Error);
}
}

}





and in the errortext.aspx

private void Page_Load(object sender, System.EventArgs e)
{
throw new Exception("An error occurred in the " +
"Page_Load of the TestLogging page.");

}

plz get me out
On Tuesday, February 06, 2007 1:04:49 PM Imar Spaanjaars said:
Sorry, I can't read this. I suggest you post this on a forum like http://p2p.wrox.com

Imar
On Wednesday, February 07, 2007 10:25:59 AM Roshan said:
ok thanks
On Sunday, February 18, 2007 11:38:22 AM Sajjad said:
nice article, but it gives only last error, what if i am calling two functions in Page_Load event and both contains error, but Server.GetLastError() will only return the Last exception. so how can i get the all erros
On Sunday, February 18, 2007 11:45:00 AM Imar Spaanjaars said:
Hi Sajjad,

You can't have "two errors". When an exception occurs, you either catch and handle it, or you don't. If you handle it, it won't bubble up to code in Global.asax and if you don't handle it, the code in Global.asax is triggered on the *first* exception....

Cheers,

Imar
On Tuesday, February 20, 2007 8:03:08 AM Sajjad said:
thanx, got it.
On Friday, April 13, 2007 8:42:44 PM Sirisha said:
Wonderful article!!!!
On Sunday, November 25, 2007 9:29:12 AM karthik said:
Application using Asp.net.2

Iam getting error on line EventLog.CreateEventSource(,,);

Below is the error

System.Security.SecurityException was unhandled by user code
  Message="The source was not found, but some or all event logs could not be searched.  Inaccessible logs: Security."
  Source="System"
  StackTrace:
       at System.Diagnostics.EventLog.FindSourceRegistration(String source, String machineName, Boolean readOnly)
       at System.Diagnostics.EventLog.SourceExists(String source, String machineName)
       at System.Diagnostics.EventLog.CreateEventSource(EventSourceCreationData sourceData)
       at System.Diagnostics.EventLog.CreateEventSource(String source, String logName)
       at cls_EventLog.Create_Event(String ErrorMessage) in d:\Current\Matrimonial_site\Matrimonial\App_Code\cls_EventLog.cs:line 29
       at MM_Home.FirstEntry() in d:\Current\Matrimonial_site\Matrimonial\MM\Home.aspx.cs:line 30
       at MM_Home.Page_Load(Object sender, EventArgs e) in d:\Current\Matrimonial_site\Matrimonial\MM\Home.aspx.cs:line 24
       at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
       at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
       at System.Web.UI.Control.OnLoad(EventArgs e)
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
On Sunday, November 25, 2007 10:34:23 AM Imar Spaanjaars said:
Hi karthik,

Current versions of ASP.NET are much more strict when it comes to security than they were when I wrote this article.

Take a look here for some ideas on how to fix this:

http://www.jameskovacs.com/blog/PermaLink.aspx?guid=cd6e5f6e-7107-48bc-8563-f5669706fcdc

Cheers,

Imar
On Friday, February 22, 2008 12:55:15 AM Trevor said:
I was wondering if there is a way to log all exceptions including ones that are handled, for instance if I have a try catch code that handles the error correctly is there a way to log that without having to add the log code to every try statement?

Thanks

Trevor.
On Saturday, February 23, 2008 9:24:17 AM Imar Spaanjaars said:
Hi Trevor,

AFAIK, you can't. When you handle the exception, the run-time no longer is aware of it.

Imar
On Saturday, March 08, 2008 8:45:27 AM George said:
http://www.codeproject.com/KB/aspnet/EventViewerListener.aspx
On Saturday, March 08, 2008 8:53:47 AM George said:
The link shows a way to resolve the security issues.

For Trevor: it is possible to keep the code clean if you create a custom listener. In catch blocks you need to write call trace method from diagnostics.
On Thursday, June 26, 2008 7:22:02 PM Dennis said:
Hi Imar,

Great article.  I added this error logic to a recent project. One question.  I have a asp.net 1.1  page that has many controls, and when there is an error in the data layer, I throw the exception, but the Application Error in Global.asax won't fire, so the error is not written to the event log.  On a simpler page in the application, I do the same as above and it works great.  How can I go about tracking down the problem?  Can multiple postbacks cause this problem?

Thanks
Dennis
On Sunday, June 29, 2008 8:52:45 AM Imar Spaanjaars said:
Hi Dennis,

Maybe you are catching the exception somewhere else? Have you tried debugging the site and stepping through the code?

Imar
On Friday, October 31, 2008 11:00:58 PM Iqbal said:
Hi Sir,
Please I successfully wrote a java program to take and save pictures from front view camera of my phone Nokia 6220 classic.
Please when I execute my API/Jar file, security warning/pop up messages come, which must not be.
Please let me know that how I can stop/by pass these warning/pop up messeges.
Please my project submission date is too close, kindly help me.
I will appreciate.
On Saturday, November 01, 2008 9:30:14 AM Imar Spaanjaars said:
Hi Iqbal,

Heuh? What? How do you see this related to logging errors in ASP.NET? If you're really in a hurry, why don't you spend some time finding the right forum or web site to ask these kind of questions? Right now, you're only wasting oher people's time...

Anyway, it's all explained here in detail:

http://imar.spaanjaars.com/QuickDocId.aspx?quickdoc=423

Cheers,

Imar
On Wednesday, November 05, 2008 10:05:32 PM pranjal said:
This was a wonderful article. However, If I  prefer to write to "Application" Log and below is the code.
In Application_Error:

    string eventLog = "Application";
    string eventSource = "http://mywebsiteurl";
It executes fine. but the below line returns false:
if (EventLog.SourceExists(eventSource))

so it doesnot write to the application log. Help.....Thanks
On Thursday, November 06, 2008 7:43:43 AM Imar Spaanjaars said:
Hi pranjal,

Sounds like a permissions issue. Search Google for "asp.net write eventlog permissions" and you'll find some useful stuff about configuring permissions.

Hope this helps,

Imar
On Thursday, November 06, 2008 4:24:33 PM pranjal said:
Hi Imar,

I just followed a link:
http://support.microsoft.com/default.aspx?scid=kb%3Ben-us%3B329291

Helped me solve my problem . Also I removed the if sourceExists condition and replaced the code with following:
string eventSource = "Test";
EventLog myLog = new EventLog(eventLog);
                    myLog.Source = eventSource;
                    EventLog.CreateEventSource(myLog.Source,"Application");
                {
                    myLog.WriteEntry("An error occured in the web application" + eventSource + "\r\n\r\n" + myErrorMessage, EventLogEntryType.Error);
               }

It works fine. Thank you so much for the help.
On Tuesday, May 19, 2009 12:43:20 PM Saravanan V said:
Hello Mr.Imar,
I read your article " Logging Errors to the Event Log in ASP.NET Applications" today.

I have a doubt and please clarify it.
Before going to the actual doubt, i will briefly explain what i have done in my web appln project.

I'm working in a web appln projec using ASP.NET 1.1 c# and SQL 2005 tech.
I wanted to publish the exception in a text filer in the server. So, i copied the 2 DLLs Microsoft.ApplicationBlocks.ExceptionManagement and Microsoft.ApplicationBlocks.ExceptionManagement.Interfaces from one of my friend's project and i have pasted the same in the bin folder.

I have included a class file which is implementing the interface "IExceptionPublisher". I am using the line "ExceptionManager.Publish(ex);" in the catch block. This publishes the exception details in a text and also in the "application" event log perfectly.

Now, coming back to my doubt, please refer to the below lines in your article.

The Application Block may be a bit overwhelming at first, and difficult to install and configure if you don't read the documentation carefully.

You are saying that we need to install the application block. I don't understand what is this and why it is required ?

Eventhough i am not logging the exception in event log i just want to this.

Please look into this and help me.

Thanks,
Saravanan V.
On Sunday, May 24, 2009 10:10:57 AM Imar Spaanjaars said:
Hi Saravanan,

This article is from 2004; back then the application blocks were sometimes very difficult to install, especially on a production server.

Cheers,

Imar
On Thursday, September 03, 2009 6:34:56 PM Mike Durthaler said:
There is one thing that any post I've found has omitted: In dev, one is using a SINGLE machine.  Live, there could be many.

I just called our host and the tech there ran a script where the machine name had to be specified.  There was an error solved: My app log events all wrote locally but did not on the server.

I added this to the code I found on another post:                 objEventLog.MachineName = System.Environment.MachineName

A good thing for people to remember is a hosting environment is proabably a server farm -- we better say WHICH app log we want to write to!  This occurred to me as the DBA running the script was specifying a machine name.

This, again, is not mentioned on any of the 4 posts I've seen on this topic.  So ... it is now. :)

Public Function WriteToEventLog( _
            ByVal Entry As String, _
            Optional ByVal AppName As String = "", _
            Optional ByVal EventType As EventLogEntryType = EventLogEntryType.Information, _
            Optional ByVal LogName As String = "Application") As Boolean

            Dim objEventLog As New EventLog

            Try
                'Register the App as an Event Source
                If Not EventLog.SourceExists(AppName) Then

                    EventLog.CreateEventSource(AppName, LogName)
                End If

                objEventLog.Source = AppName

                objEventLog.MachineName = System.Environment.MachineName
                'WriteEntry is overloaded; this is one
                'of 10 ways to call it
                objEventLog.WriteEntry(Entry, EventType)

                Return True
            Catch Ex As Exception

                Return False

            End Try
        End Function
On Friday, February 19, 2010 11:56:22 AM Paul said:
Hey dude nice article.

Who wants to be stinkin' rich, laying on the beach somewhere drinking a Bacardi and Coke, instead of reading this article? Not me I'd much rather be here stuck at the office in cold, wet, wintry England!
On Tuesday, August 28, 2012 8:24:28 AM Jayesh Sorathia said:
This is really a very good article.
To learn more regarding Read and Write events from Event Logs in ASP.Net visit this link.
http://jayeshsorathia.blogspot.com/2012/08/net-tips-write-event-entry-in-windows-event-log.html
On Wednesday, April 10, 2013 6:32:38 PM asava samuel said:
This is a great logging library:
http://www.kellermansoftware.com/p-14-net-logging-library.aspx

Talk Back! Comment on Imar.Spaanjaars.Com

I am interested in what you have to say about this article. Feel free to post any comments, remarks or questions you may have about this article. The Talk Back feature is not meant for technical questions that are not directly related to this article. So, a post like "Hey, can you tell me how I can upload files to a MySQL database in PHP?" is likely to be removed. Also spam and unrealistic job offers will be deleted immediately.

When you post a comment, you have to provide your name and the comment. Your e-mail address is optional and you only need to provide it if you want me to contact you. It will not be displayed along with your comment. I got sick and tired of the comment spam I was receiving, so I have protected this page with a simple calculation exercise. This means that if you want to leave a comment, you'll need to complete the calculation before you hit the Post Comment button.

If you want to object to a comment made by another visitor, be sure to contact me and I'll look into it ASAP. Don't forget to mention the page link, or the QuickDocId of the document.

For more information about the Talk Back feature, check out this news item.