Click here to Skip to main content
15,885,881 members
Articles / Programming Languages / C# 4.0

How To Create a Windows Event Log and Write your Custom Message as well

Rate me:
Please Sign up or sign in to vote.
4.92/5 (40 votes)
22 Aug 2009CPOL2 min read 200K   4.4K   79   13
A simple class to create a Windows event log and write your custom message as well
Event.png
Fig-1 (Event viewer - Showing the new log with sample information)

Introduction

This article will give you an idea about how to create a Windows event log and write your custom message into the event log.

Background

Most of the developers are very much familiar with the Windows event log API. When developers create a Windows based application, it may be an ActiveX component, any customized DLL library, a service application, etc.; it is a very common practice to write several types of information into the event log, which is generated by that particular application runtime so we can easily keep track of all the information.

Using the Code

Before we start understanding the code, we need a little concept on System.Diagnostics namespace. We will use the namespace to manage an event log. The namespace System.Diagnostics provides a class name as “EventLog” to create and write a message into the eventlog.

Let’s take an example, our goal is to write a simple C# .NET class which will create a new log name as “myEventLog” and write a message “I will not say I have failed 1000 times; I will say that I have discovered 1000 ways that can cause failure – Thomas Edison.” as an information.

To achieve this, we need to use the following methods, properties and enum which will be found in the System.Diagnostics namespace.

Methods

  • SourceExists: Determines whether an event source is registered on the local computer or not.
  • CreateEventSource: Establishes an application as able to write event information to a particular log on the system.
    More details can be found at this link.
  • WriteEntry: Writes an entry in the event log, i.e., writes an information type entry, with the given message text, to the event log.
    More details can be found at this link.

Properties

  • Source: Gets or sets the source name to register and use when writing to the event log.
  • Log: Gets or sets the name of the log to read from or write to.

Enum

  • EventLogEntryType: Specifies the event type of an event log entry.
    More details can be found at this link.

Sample Code Example

C#
public class ClsEventLog
  {
      public bool CreateLog(string strLogName)
      {
          bool Result = false;

          try
          {
                  System.Diagnostics.EventLog.CreateEventSource(strLogName, strLogName);
                  System.Diagnostics.EventLog SQLEventLog =
              new System.Diagnostics.EventLog();

                  SQLEventLog.Source = strLogName;
                  SQLEventLog.Log = strLogName;

                  SQLEventLog.Source = strLogName;
                  SQLEventLog.WriteEntry("The " + strLogName + " was successfully
          initialize component.", EventLogEntryType.Information);

                  Result = true;
          }
          catch
          {
              Result = false;
          }

          return Result;
      }
      public void WriteToEventLog(string strLogName
                                , string strSource
                                , string strErrDetail)
      {
          System.Diagnostics.EventLog SQLEventLog = new System.Diagnostics.EventLog();

          try
          {
              if (!System.Diagnostics.EventLog.SourceExists(strLogName))
                      this.CreateLog(strLogName);


              SQLEventLog.Source = strLogName;
              SQLEventLog.WriteEntry(Convert.ToString(strSource)
                                    + Convert.ToString(strErrDetail),
              EventLogEntryType.Information);

          }
          catch (Exception ex)
          {
              SQLEventLog.Source = strLogName;
              SQLEventLog.WriteEntry(Convert.ToString("INFORMATION: ")
                                    + Convert.ToString(ex.Message),
              EventLogEntryType.Information);
          }
          finally
          {
              SQLEventLog.Dispose();
              SQLEventLog = null;
          }
      }
  }

Conclusion

I hope that this article might be helpful to you. Enjoy!

History

  • 22nd August 2009: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
GeneralWindows Event Log Custom Message Pin
GauravKM8-Dec-17 2:28
professionalGauravKM8-Dec-17 2:28 
GeneralMy vote of 5 Pin
deatharthas3-Dec-12 15:47
deatharthas3-Dec-12 15:47 
GeneralRe: My vote of 5 Pin
Md. Marufuzzaman4-Dec-12 4:57
professionalMd. Marufuzzaman4-Dec-12 4:57 
GeneralMy vote of 5 Pin
Joe Sam27-Nov-12 19:47
Joe Sam27-Nov-12 19:47 
GeneralRe: My vote of 5 Pin
Md. Marufuzzaman28-Nov-12 7:49
professionalMd. Marufuzzaman28-Nov-12 7:49 
GeneralMy vote of 5 Pin
JF20155-Jun-12 20:48
JF20155-Jun-12 20:48 
GeneralRe: My vote of 5 Pin
Md. Marufuzzaman28-Nov-12 7:47
professionalMd. Marufuzzaman28-Nov-12 7:47 
GeneralMy vote of 5 Pin
Prasanta_Prince14-Jul-11 19:12
Prasanta_Prince14-Jul-11 19:12 
GeneralRe: My vote of 5 Pin
Md. Marufuzzaman5-Oct-11 23:13
professionalMd. Marufuzzaman5-Oct-11 23:13 
GeneralGreat Pin
shahadatbjri25-Aug-09 8:54
shahadatbjri25-Aug-09 8:54 
GeneralRe: Great Pin
Md. Marufuzzaman23-May-10 22:09
professionalMd. Marufuzzaman23-May-10 22:09 
GeneralPermissions Pin
Grand Poobah 7722-Aug-09 7:54
Grand Poobah 7722-Aug-09 7:54 
Good article in an area many people aren't aware of. It's important to note when working with the event log that elevated permissions are required to create an event log. If this code were deployed in an application to an end user running as a local user in Windows or as part of a server application running with minimal security access the log won't be created.

You have a "catch all" try block which will stop this from breaking the hosting application but anyone implementing it needs to know that you need elevated permissions for this code to function properly. In previous enterprise scenarios I had created a separate tool to deal with creating the log which the migration team used to make sure the event log was in place on all servers/boxes before deployment of the new/updated application.

That may not be a good idea in some scenarios. If they run into that a possible solution is to have a service running which you can invoke which handles logging such as this and does have the proper permissions.

From MSDN
"To create an event source in Windows Vista, Windows XP Professional, or Windows Server 2003, you must have administrative privileges.

The reason for this requirement is that all event logs, including security, must be searched to determine whether the event source is unique. In Windows Vista, users do not have permission to access the security log; therefore, a SecurityException is thrown.

In Windows Vista, User Account Control (UAC) determines the privileges of a user. If you are a member of the Built-in Administrators group, you are assigned two run-time access tokens: a standard user access token and an administrator access token. By default, you are in the standard user role. To execute the code that accesses the security log, you must first elevate your privileges from standard user to administrator. You can do this when you start an application by right-clicking the application icon and indicating that you want to run as an administrator."
GeneralRe: Permissions Pin
Md. Marufuzzaman22-Aug-09 10:17
professionalMd. Marufuzzaman22-Aug-09 10:17 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.