Writing to the Windows Event Log with C# .NET

In this post we saw how to create and delete event logs. We’ve also seen a couple examples of writing to the event log. Here come some more examples.

Say you want to send a warning message to the System log:

string source = "DemoSourceWithinApplicationLogSystem";
EventLog systemEventLog = new EventLog("System");
if (!EventLog.SourceExists(source))
{
	EventLog.CreateEventSource(source, "System");
}
systemEventLog.Source = source;
systemEventLog.WriteEntry("This is warning from the demo app to the System log", EventLogEntryType.Warning, 150);

As there is no such source yet in any event log it must be registered first. In the CreateEventSource method you can specify which log the source will belong to. The WriteEntry method has 5 overloads, of which you can see one above with a message, an entry type and an event ID. The event ID is an arbitrary integer that you can specify. It is an optional parameter which is set to 0 by default. The warning occurs like this in the event viewer:

Writing a warning to the System log

Say you’d like to send a warning message to the Application log instead with no event ID:

string source = "DemoSourceWithinApplicationLog";
string log = "Application";
if (!EventLog.SourceExists(source))
{
	EventLog.CreateEventSource(source, log);
}
EventLog.WriteEntry(source, "This is a warning from the demo log", 
	EventLogEntryType.Warning);

Here it is:

Writing a warning to the application log

If you know that the source has already been registered then you can send a message in a shorter format:

string source = "DemoSourceWithinApplicationLog"
EventLog.WriteEntry(source, "This is an error messsage from the demo log", EventLogEntryType.Error, 100);

Error message in application log

You can view all posts related to Diagnostics here.

Advertisement

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

One Response to Writing to the Windows Event Log with C# .NET

  1. Chris says:

    I have a application that my dev team put out that is configured this way. Although the only way we can get the log into event viewer is to be local admin on the application server. Any ideas?

Leave a Reply

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

WordPress.com Logo

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

Twitter picture

You are commenting using your Twitter 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

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

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

%d bloggers like this: