25 November 2008

C# Event Log Write To EventLog Entry

Write to event log in C#
  • Add reference using System.Diagnostics to your project
  • Check whether the source exits or not.
  • If not create event source.
  • Create an EventLog object.
  • Set its event source.
  • Write the entry into event source.
C# sample source code is below;

using System.Diagnostics;

private void WriteToEventLog(string message)
string cs = "Your Source Name";
EventLog elog = new EventLog();

if (!EventLog.SourceExists(cs))
EventLog.CreateEventSource(cs, cs);

elog.Source = cs;
elog.EnableRaisingEvents = true;

C# Event Log Write To EventLog Entry tutorial


Anonymous said...

So Now How can i see this created log file?

Acertijo said...

You could access the "Event Viewer" by right-cliking "My PC" and choosing "administrate"

Anonymous said...

I tried this, but could not make it work.

It turned out that EventLog.SourceExists throws security exception in windows 7.

Running the application as administrator solves the problem.

Anonymous said...

Ah, eventlogs, I hate them...

- when you create a source, you must have administrator rights. Because method that checks if source exists looks through EVERY log in the system, including Security (which you can't touch if you're not administrator).

- it's better to not create logs with the same name as it's source's name (or any other source's name). I don't know why exactly but better not do that. It's asking for problems. (I usually create logs with names [SourceName + "Log"]).

- The first 8 characters of the source name must be unique. So if you create 3 sources named "MySource1", "MySource2", "MySource3" it will throw an exception.

- you have to be careful when subscribing to EntryWritten event (if you want to read from the log). Sometimes it behaves strangely - for example when log is cleared manually from windows event viewer EntryWritten event can get "unsubscribed" on it's own.

samuel fernandes said...


Generally we are not interested to show any type of application error to end user. Error logs are very important for collecting all error data generated by an

application. It is more useful during an early or beta release of a product. That’s why it is better to store any kind of exceptions in one place. This files can be

send by email or others technology to developer. Time to time developer must analyze them and fix all the bugs without knowing clients. It will increase application

performance. So thanks for sharing your knowledge. There are few other links that helpful for developers.