Writing To The Windows Event Log Using C#

Operating System

The Windows Event Log is a great place to log your application’s errors or major events because it is easily accessible by administrators since all Windows Event logs can be managed from the same console. This makes the administrator’s life easier because he/she does not have to monitor logs stored in multiple directories all over the place. However, if your application generates large amounts of logs, I recommend you create your own logging system instead, so as not to over clutter the Windows Event Logs.

In this short article I am going to show you how to write to the Windows Event Log. It is actually quite simple – all you have to do is use the .NET System.Diagnostics.EventLog class.

Below is an example of how to use this class to write to the log:

static void Main(string[] args)
{
    WriteEventLogEntry("This is an entry in the event log by daveoncsharp.com");
}

private static void WriteEventLogEntry(string message)
{
    // Create an instance of EventLog
    System.Diagnostics.EventLog eventLog = new System.Diagnostics.EventLog();

    // Check if the event source exists. If not create it.
    if (!System.Diagnostics.EventLog.SourceExists("TestApplication"))
    {
        System.Diagnostics.EventLog.CreateEventSource("TestApplication", "Application");
    }

    // Set the source name for writing log entries.
    eventLog.Source = "TestApplication";

    // Create an event ID to add to the event log
    int eventID = 8;

    // Write an entry to the event log.
    eventLog.WriteEntry(message,
                        System.Diagnostics.EventLogEntryType.Error,
                        eventID);

    // Close the Event Log
    eventLog.Close();
}

In the WriteEventLogEntry method we are creating an instance of the System.Diagnostics.EventLog class. Then we are using the EventLog.SourceExists method to check whether the event source “TestApplication” is registered. If it is not registered we are creating it under the “Application” event log. This means that our logged events will appear under the Application event log and the event source will show TestApplication.

Next we are setting the source name and then we are creating an event id. The event id is just a numerical value which will be displayed in the event log. It is designed to be used by the developer for tracking application events. For example you can assign an event number to an error – like 1 if a connection fails, 2 if a file is not found, 3 if a file is locked, etc. Then you pass this event id when writing a log entry and the logs will display it. This way you can get more detailed information about the error.

Finally we are calling the WriteEntry method and passing the details to create the event log, and then we are closing our connection to the event log.

After running the application you should see an entry similar to this in the Windows Event Viewer:

Event Log Entry

Accessing the Event Log in Windows Vista

Because of the added security features in Windows Vista you cannot access the event log by just using the above code. You must add an app.manifest file to your application. A manifest file, among other things, allows you to access Windows Vista restricted areas a little easier.

Add an Application Manifest File from the Add New Item section in Visual Studio and you will end up with an XML file which looks like this:

<?xml version="1.0" encoding="utf-8"?>
<asmv1:assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1" xmlns:asmv1="urn:schemas-microsoft-com:asm.v1" xmlns:asmv2="urn:schemas-microsoft-com:asm.v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
    <security>
      <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
        <!-- UAC Manifest Options
            If you want to change the Windows User Account Control level replace the 
            requestedExecutionLevel node with one of the following.

        <requestedExecutionLevel  level="asInvoker" uiAccess="false" />
        <requestedExecutionLevel  level="requireAdministrator" uiAccess="false" />
        <requestedExecutionLevel  level="highestAvailable" uiAccess="false" />

            If you want to utilize File and Registry Virtualization for backward 
            compatibility then delete the requestedExecutionLevel node.
        -->
        <requestedExecutionLevel level="asInvoker" uiAccess="false" />
      </requestedPrivileges>
    </security>
  </trustInfo>
</asmv1:assembly>

Now edit the <requestedExecutionLevel level="asInvoker" uiAccess="false" /> line to use requireAdministrator instead of asInvoker and you’re done.

In Windows Vista, the User Access Control (UAC) causes processes to run as a standard user even if you are logged in with a user that is a member of the Administrators group. This entry in the manifest file lets Windows know that you want to run your application as an administrator. And as an administrator you have full access to the Windows Event Log :). The only drawback is that you cannot run this application if the user executing it is not a member of the Administrators group.

I hope you enjoyed this article. Stay tuned for more soon.

Dave

10 comments… add one
  • J.C Link Reply
    • This code will not work under Windows Vista or newer. You need to add a manifest file and run your code with administrator privileges – then it will work 🙂

      Cheers
      Dave

  • You cannot change “asInvoker” to “requireAdministrator” for a ClickOnce deployment.

    • ClickOnce is designed to be used for installing applications which are installed per-user, and not per-machine. These type of installations should not require administrative permissions.

      I haven’t tried installing this example with a ClickOnce installation, so I am not too sure what error is returned, but since this example requires administrative privileges to access the Windows Event Log, I assume ClickOnce is not the right deployment option.

  • ClickOnce applications may need to write to the Application log. The way in which MS searches for the existence of the log causes it to reference an admin restricted log (Security), which results in an error.

  • website Link Reply

    Oh my goodness! Awesome article dude! Thank you so much, However I
    am experiencing problems with your RSS. I don’t know the
    reason why I am unable to join it. Is there anybody else getting similar RSS
    problems? Anybody who knows the solution will you kindly respond?
    Thanx!!

Leave a Comment

Cancel reply