Write to Windows Event Viewer from C#

Leave a comment

First, create a new console app:

Next, add:

using System.Diagnostics;

Notice the Event Viewer in Windows has several areas:

  • Windows Logs, which are:
    • Application
    • Security
    • Setup
    • System
    • Forwarded Events

And within each log, there are:

  • Keywords
  • Date and Time
  • Source
  • Event Id
  • Task Category

To write to the application log, use the code:

        static void Main(string[] args)
        {
            string Event = "Application has started";

            using (EventLog eventLog = new EventLog("Application"))
            {
                eventLog.Source = "Application";
                eventLog.WriteEntry(Event, EventLogEntryType.Information);
            }
        }

This will write to the Application log. Note the event id is not found for the new application:

In order to create a new log in the event viewer, use the code below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
 
namespace Carl.EventViewerTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string Event = "Application has started";
            string Source = "My App";
            string Log = "App";
 
            if (!EventLog.SourceExists(Source))
                EventLog.CreateEventSource(Source, Log);
 
            using (EventLog eventLog = new EventLog("App"))
            {
                eventLog.Source = "My App";
                eventLog.WriteEntry(Event, EventLogEntryType.Information);
            }
        }
    }
}

Notice there is a new log, “App” created under Applications and Service Logs:

 

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn
Filed under: C#

Leave a Reply

Your email address will not be published. Required fields are marked *

4 × one =