How to Write to Windows Event Log

Ever wondered how to write to Windows event log? It’s quite easy! The System.Diagnostics namespace provides you with what you need. All you need is the name of your application which is going to show under the Source column, the message you want to write to the log, optionally the name of the log (that is, System, Application, a custom name, etc.) and optionally the event id. Let’s give it a go:

using System;
using System.Diagnostics;

namespace MyEventLogMessage
	class Program
		static void Main()
			const string appName = "MyEventLogMessageApplication";
			const string logName = "Application";
			const string logMessage = "Hello event log!";
			const int eventId = 12345;
			if (!EventLog.SourceExists(appName)) { EventLog.CreateEventSource(appName, logName); }
			EventLog.WriteEntry(appName, logMessage, EventLogEntryType.Information, eventId);

Well, now, there’s a couple of more optional parameters that you can pass, but I’ll let you intellisense those.

This entry was posted in System and tagged , , , , , . Bookmark the permalink.

Leave a Reply

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