Read Event Viewer logs using C#

Read Event Viewer logs using C#


 Below demonstrated code helps to read logs data from event viewer and stores in database using entity framework.

Database table

CREATE TABLE [dbo].[EventLogData](
 [Id] [int] IDENTITY(1,1) NOT NULL,
 [EventId] [nvarchar](10) NULL,
 [EventType] [nvarchar](50) NULL,
 [Site] [nvarchar](200) NULL,
 [Source] [nvarchar](500) NULL,
 [TimeGenerated] [datetime] NULL,
 [Message] [ntext] NULL,
 CONSTRAINT [PK__EventLog__3214EC07A20289BA] PRIMARY KEY CLUSTERED 
(
 [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

Code


namespace EventLogsDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            EventLog log = new EventLog("Application");
            var entries = log.Entries.Cast<EventLogEntry>()
                                     // .Where(x => x.InstanceId == 4624)
                                     .Select(x => new
                                     {
                                         x.EventID,
                                         x.EntryType,
                                         x.Site,
                                         x.Source,
                                         x.TimeGenerated,
                                         x.Message
                                     })
                                      .ToList();

            List<EventLogData> eventLogDatas = new List<EventLogData>();
            EventLogData eventLogData;

            Console.WriteLine("Total Entries : " + entries.Count.ToString());
            foreach (var item in entries)
            {
                eventLogData = new EventLogData()
                {
                    EventId = Convert.ToString(item.EventID),
                    EventType = Convert.ToString(item.EntryType),
                    Site = Convert.ToString(item.Site),
                    Source = item.Source,
                    TimeGenerated = item.TimeGenerated,
                    Message = item.Message
                };
                eventLogDatas.Add(eventLogData);
            }

            using (var db = new EventsEntities())
            {
                db.Database.ExecuteSqlCommand("TRUNCATE TABLE EventLogData");

                db.EventLogDatas.AddRange(eventLogDatas);
                db.SaveChanges();
            }


            Console.WriteLine("Process completed. Press any key to continue...");
            Console.Read();
        }
    }
}

Hope this will help you and save your time.

Enjoy !!!

:)

No comments:

Post a Comment