Friday, September 11, 2009

ASP.NET - EventLog Class - Custom logs


It's a good idea to log errors and unexpected conditions in event log. But if you want to record user actions or other data which repeats a lot and consume considerable amount of space, the Event Log is not a good choice and may be it's better to log it in database tables or XML files, because Event log uses disk space and takes processor time and it will affect overall performance of machine and our application.

EventLog class in System.Diagnostics namespace allows us to utilize related functions in .NET, on the other hand, it's a good practice to make a custom errors log and record messages related to our application there. Then Event Viewer will collect messages in an individual place which allows us to keep track of them easily. the following sample code implements custom event logging idea.

try
{
// ...
// you code here
// ...
}
catch (Exception ex)
{
string logName = "myWebAppEventLog";
if (!EventLog.SourceExists(logName))
{
EventSourceCreationData escd =
new EventSourceCreationData("myWebAppSrc", logName);
escd.MachineName = System.Environment.MachineName;
EventLog.CreateEventSource(escd);
}
EventLog evntLog = new EventLog(logName);
evntLog.Source = "myWebApp";
evntLog.WriteEntry(ex.Message, EventLogEntryType.Error);
}


To find more you can take a look at following URLs and or search online.
- EventLog Class
http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog%28VS.71%29.aspx

- How to manage event logs using Visual C# .NET or Visual C# 2005
http://support.microsoft.com/kb/815314

- Security Ramifications of Event Logs
http://msdn.microsoft.com/en-us/library/4xz6w79h%28VS.71%29.aspx
Share/Bookmark

No comments: