LINQ to read eventlogs from C#

Posted: March 17, 2011 in LINQ

My previous post if you had seen,I talked about writing  eventlogs using Log4Net.You can always use the Windows Event Viewer to see the logs.But in case you cannot directly login to machine,you may want to read the logs from code.Here I am sharing a codesnippet on how you you can read using LINQ and bind to a gridview control.

            eventlog.MachineName = whichmachine;
           //this reads the name from a dropdown say for eg Application logs you selected
            eventlog.Log = ddleventlogs.Items[ddleventlogs.SelectedIndex].Value.ToString();
            //queries logs under Application from a selected source         
            var query = from EventLogEntry eventlogentry in eventlog.Entries
                        where eventlogentry.Source == ddleventsource.Text
                        select new
                            Time = eventlogentry.TimeGenerated,
                            Source = eventlogentry.Source,
                            Message = eventlogentry.Message

            eventviewgrid.DataSource = query.ToList();

Is that not simple?LINQ rocks always 🙂

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 )

Google photo

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