Creating and deleting event logs with C# .NET

The Windows event viewer contains a lot of useful information on what happens on the system:

Windows event viewer

Windows will by default write a lot of information here at differing levels: information, warning, failure, success and error. You can also write to the event log, create new logs and delete them if the code has the EventLogPermission permission. However, bear in mind that it’s quite resource intensive to write to the event logs. So don’t use it for general logging purposes to record what’s happening in your application. Use it to record major but infrequent events like shutdown, severe failure, start-up or any out-of-the-ordinary cases.

There are some predefined Windows logs in the event log: Application, Security and System are the usual examples. However, you can create your own custom log if you wish. The key is the EventLog object located in the System.Diagnostics namespace:

string source = "DemoTestApplication";
string log = "DemoEventLog";
EventLog demoLog = new EventLog(log);
demoLog.Source = source;
demoLog.WriteEntry("This is the first message to the log", EventLogEntryType.Information);

The new log type was saved under the Applications and Services log category:

First custom log

You’ll probably have to restart the Event Viewer to find the new log type.

You can write to one of the existing Windows logs as well by specifying the name of the log. So we can create a log source within the Application log as follows:

string source = "DemoSourceWithinApplicationLog";
string log = "Application";
if (!EventLog.SourceExists(source))
	EventLog.CreateEventSource(source, log);
EventLog.WriteEntry(source, "First message from the demo log within Application", EventLogEntryType.Information);

The log entry is visible within the Application log:

Log entry in the Application log

It’s very easy to delete your custom log:

string log = "DemoEventLog";

The log will be deleted. Again, you’ll have to restart the event viewer to see that changes.

You can view all posts related to Diagnostics here.


About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: