- 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.
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;
elog.WriteEntry(message);
}
C# Event Log Write To EventLog Entry tutorial
5 comments:
So Now How can i see this created log file?
You could access the "Event Viewer" by right-cliking "My PC" and choosing "administrate"
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.
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.
Hi!
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.
http://www.mindstick.com/Blog/458/How%20to%20Create%20Log%20File%20in%20C
http://cybarlab.blogspot.in/2013/03/write-error-log-into-file-in-c-sharp.html
http://www.codeproject.com/Articles/2344/Create-Simple-Error-Log-Files-using-ASP-NET-and-C
Post a Comment