private void LoadLogFromEventLog(DateTime?dateTime) { LogPresenterList.Clear(); EventLogEntryCollection applicationEntries = EventLog.GetEventLogs().FirstOrDefault(f => f.LogDisplayName == "Application").Entries; IEnumerable <EventLogEntry> beSafeLogEntries = applicationEntries.Cast <EventLogEntry>().Where(w => w.Source == Resources.ApplicationName && w.InstanceId == BeSafe_Log_EventID); List <EventLogEntry> beSafeLogsFilteredByDate = (dateTime != null) ? beSafeLogEntries.Where(w => w.TimeWritten.Date.CompareTo(dateTime.Value.Date) == 0).ToList() : beSafeLogEntries.ToList(); foreach (EventLogEntry ev in beSafeLogsFilteredByDate) { if (!ev.Data.Any()) { continue; } PluginResult pluginResult = Deserialize <PluginResult>(ev.Data); LogPresenterList.Add(new LogPresenter { Date = ev.TimeWritten, ScannedObject = pluginResult.ScannedObjectString, PluginName = pluginResult.PluginInfo.ToString(), Risk = pluginResult.RiskRate, PluginMessage = pluginResult.Message, }); } logPresenterBindingSource.DataSource = LogPresenterList.ToList(); }
public DataTable GetEventLogs(string serviceName) { try { DataTable dataTableEvents = new DataTable("EventLogs"); dataTableEvents.Columns.Add("ServiceName"); dataTableEvents.Columns.Add("Message"); dataTableEvents.Columns.Add("TimeGenerated"); EventLog[] eventLogs = EventLog.GetEventLogs(); foreach (EventLog eventLog in eventLogs) { EventLogEntryCollection entries = eventLog.Entries; for (int i = entries.Count - 1; i >= 0; i--) { if (entries[i].Source.Trim().ToUpper() == serviceName.Trim().ToUpper()) { DataRow dataRow = dataTableEvents.NewRow(); dataRow["ServiceName"] = serviceName; dataRow["Message"] = entries[i].Message; dataRow["TimeGenerated"] = entries[i].TimeGenerated; dataTableEvents.Rows.Add(dataRow); } } } return(dataTableEvents); } catch (Exception ex) { ExceptionManager.Publish(ex); return(new DataTable("Error")); } }
//--------------------------------------------- // Очистка выбранного журнала //--------------------------------------------- public void EventLogClear(TreeView aTreeView, DataGridView aDataGridView) { logDataGridView = aDataGridView; logDataGridView.Rows.Clear(); string tmp = ""; string logType = ""; int k = 0; if (logTreeView.SelectedNode != null) { tmp = logTreeView.SelectedNode.Text; k = tmp.IndexOf(" ("); if (k != 0) logType = tmp.Substring(0, k); //EventLog ev = server.GetEventLog(logType); //int LastLogToShow = ev.Entries.Count; EventLogEntryCollection logEntries = server.GetEventLogEntries(logType); int LastLogToShow = logEntries.Count; if (LastLogToShow <= 0) { string message = "В журнале: " + logType + " записи уже отсутствуют"; string caption = "Очистка журналов событий"; MessageBox.Show(message, caption, MessageBoxButtons.OK, MessageBoxIcon.Information); } else { //ev.Clear(); //ev.Close(); } } else MessageBox.Show("Ни один журнал не выбран", "Очистка журналов событий", MessageBoxButtons.OK, MessageBoxIcon.Information); }
private void btnGetDayHours_Click(object sender, EventArgs e) { txtHoursDay.Text = "0"; try { EventLog user_log = new EventLog("Security"); EventLogEntryCollection sec_events = user_log.Entries; btnGetDayHours.Enabled = false; if (sec_events.Count < 1) { MessageBox.Show("No events in Security Event Log! Please enable audit security events.", "Audit Worktime", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } txtHoursDay.Text = GetDayHours(sec_events, selected_date); } catch (Exception ex) { MessageBox.Show("Error " + ex.Message, "Audit Worktime", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } finally { btnGetDayHours.Enabled = true; } }
private void btnReadEventLog_Click(object sender, EventArgs e) { string eventSourceName = _serviceInfo.EventSourceName; string eventLogName = _serviceInfo.EventLogName; if (System.Diagnostics.EventLog.SourceExists(eventSourceName) == false) { MessageBox.Show("Not Exist Log in system."); return; } txtProcessOutput.Text = ""; EventLog eventLog1 = new System.Diagnostics.EventLog(); eventLog1.Source = eventSourceName; eventLog1.Log = eventLogName; EventLogEntryCollection entries = eventLog1.Entries; foreach (System.Diagnostics.EventLogEntry entry in entries) { string msg = string.Format("{0} : {1}\n", entry.TimeWritten, entry.Message); txtProcessOutput.AppendText(msg); } }
private void button1_Click(object sender, EventArgs e) { String machine = "."; // local machine String log = "security"; EventLog aLog = new EventLog(log, machine); EventLogEntry entry; EventLogEntryCollection entries = aLog.Entries; Stack <EventLogEntry> stack = new Stack <EventLogEntry>(); for (int i = 0; i < entries.Count; i++) { entry = entries[i]; stack.Push(entry); listBox1.Items.Add(string.Format("{0}{1}", entry.TimeWritten, entry.Message)); } entry = stack.Pop(); // only display the last record //listBox1.Items.Add(entry.Index); //Console.WriteLine("[Index]\t" + entry.Index + // "\n[EventID]\t" + entry.InstanceId + // "\n[TimeWritten]\t" + entry.TimeWritten + // "\n[MachineName]\t" + entry.MachineName + // "\n[Source]\t" + entry.Source + // "\n[UserName]\t" + entry.UserName + // "\n[Message]\t" + entry.Message + }
/// <summary>Counts the system log events of required type</summary> /// <param name="value">the type of log event (Error, Event, Information etc)</param> /// <returns> /// Returns the number of System log entries of specified type /// </returns> public int GetSpecificEventEntriesCount(EventLogEntryType value) { // TODO : Implement GetSpecificEventEntriesCount EventLogEntryCollection systemEvents = (new EventLog("System", ".")).Entries; throw new NotImplementedException(); }
public List <EventViewerInfo> CheckParameters() { List <EventViewerInfo> eventViewerInfos = new List <EventViewerInfo>(); var today = DateTime.Now; string log = "Application"; EventLog demoLog = new EventLog(log); EventLogEntryCollection entries = demoLog.Entries; foreach (EventLogEntry entry in entries) { if ((entry.EntryType.ToString() == "Error" || entry.EntryType.ToString() == "Warning") && entry.TimeGenerated > today.AddMinutes(-4)) { EventViewerInfo eventViewerInfo = new EventViewerInfo(); eventViewerInfo.LogName = entry.EntryType.ToString(); eventViewerInfo.EventId = entry.InstanceId.ToString(); eventViewerInfo.Message = entry.Message.ToString(); eventViewerInfo.Source = entry.Source.ToString(); eventViewerInfo.LogDate = entry.TimeGenerated.ToString("yyyy-MM-dd HH:mm:ss"); eventViewerInfo.Index = entry.Index.ToString(); eventViewerInfos.Add(eventViewerInfo); } } logger.Info("Event Viewer logs checked succesfully"); return(eventViewerInfos); }
//list{ WeventID, WLevel, WSource, WCategory, WUserName, WMachineName } #endregion #region Viewchecker/Values private void GridValues(DataRow dr, EventLogEntryCollection evLog, int i) { dr["UserName"] = evLog[i].UserName; if (evLog[i].EntryType == 0) { dr["Level"] = "Information"; } else { dr["Level"] = evLog[i].EntryType; } dr["TimeWritten"] = evLog[i].TimeWritten; dr["Source"] = evLog[i].Source; //} dr["EventID"] = evLog[i].EventID; dr["Category"] = evLog[i].Category; //} dr["Message"] = evLog[i].Message; dr["MachineName"] = evLog[i].MachineName; if (evLog[i].UserName == "NT AUTHORITY\\SYSTEM") { dr["UserName"] = "******"; } else if (evLog[i].UserName == null) { dr["UserName"] = "******"; } else { dr["UserName"] = evLog[i].UserName; } }
/// <summary> /// The PopulateListOfSources sub is used to fill the LogSource drop down list /// with the different sources found in the selected event log /// </summary> private void PopulateListOfSources() { Message.Text = string.Empty; try { EventLog myEventLog = new EventLog(LogName.SelectedItem.Text, MachineName.Text); EventLogEntryCollection myLogEntryCollection = myEventLog.Entries; ArrayList mySourceArray = new ArrayList(); // Array used to sort strings before populating the drop down list; // Browse event entries for different source name foreach (EventLogEntry myLogEntry in myLogEntryCollection) { if ((mySourceArray.IndexOf(myLogEntry.Source) < 0)) { mySourceArray.Add(myLogEntry.Source); } } // // Sort the source array mySourceArray.Sort(); // Add the source names to the drop down list LogSource.Items.Clear(); LogSource.Items.Add("(all)"); foreach (string Source in mySourceArray) { LogSource.Items.Add(Source); } // // Bind grid BindGrid(); } catch { // An error as happened. Mostly permissions problems (when accessing security log for example) Message.Text = "Error while browsing source entries for " + LogName.SelectedItem.Text + ". Probably insufficient permissions"; LogSource.Items.Clear(); } }
/// <summary> /// The method reads from the machine EventLog all relevant /// Log, which are starting with eventID 1. /// </summary> /// <param name="args"></param> /// <param name="result"></param> /// <returns></returns> public string Execute(string[] args, out bool result) { Dictionary <int, string[]> map = new Dictionary <int, string[]>(); string logName = ConfigurationManager.AppSettings["LogName"]; EventLog myLog = new EventLog(logName, "."); EventLogEntry entry; EventLogEntryCollection entries = myLog.Entries; for (int i = (entries.Count - 1); i > 0; i--) { entry = entries[i]; string[] str = new string[2]; str[0] = entry.EntryType.ToString(); str[1] = entry.Message.ToString(); int.TryParse(entry.InstanceId.ToString(), out int id); map.Add(id, str); if (id == 1) { break; } } JObject logObj = new JObject { ["CommandEnum"] = (int)CommandEnum.LogCommand, ["logMap"] = JsonConvert.SerializeObject(map), ["firstTime"] = "true" }; result = true; return(logObj.ToString()); }
public void CopyingEventLogEntryCollection() { string log = "CopyCollection"; string source = "Source_" + nameof(CopyingEventLogEntryCollection); try { EventLog.CreateEventSource(source, log); using (EventLog eventLog = new EventLog()) { eventLog.Source = source; eventLog.WriteEntry(message); eventLog.WriteEntry("Further Testing"); EventLogEntryCollection entryCollection = eventLog.Entries; EventLogEntry[] entryCollectionCopied = new EventLogEntry[entryCollection.Count]; entryCollection.CopyTo(entryCollectionCopied, 0); int i = 0; foreach (EventLogEntry entry in entryCollection) { Assert.Equal(entry.Message, entryCollectionCopied[i].Message); i += 1; } } } finally { EventLog.DeleteEventSource(source); EventLog.Delete(log); } }
private void DisplayEventEntries(string logName, string machineName) { entryList.BeginUpdate(); try { this.Cursor = Cursors.WaitCursor; // remove current items entryList.Items.Clear(); // remove current columns entryList.Columns.Clear(); // create necessary columns entryList.Columns.Add("Type", 100, HorizontalAlignment.Left); entryList.Columns.Add("Date", 100, HorizontalAlignment.Left); entryList.Columns.Add("Time", 100, HorizontalAlignment.Left); entryList.Columns.Add("Source", 200, HorizontalAlignment.Left); entryList.Columns.Add("Category", 100, HorizontalAlignment.Left); entryList.Columns.Add("Event", 100, HorizontalAlignment.Left); entryList.Columns.Add("User", 100, HorizontalAlignment.Left); entryList.Columns.Add("Computer", 100, HorizontalAlignment.Left); // add eventlog entries using (EventLog eventLog = new EventLog(logName, machineName)) { EventLogEntryCollection entries = eventLog.Entries; foreach (EventLogEntry entry in entries) { EventEntryView view = new EventEntryView(entry); // most recent event log entries are at the top entryList.Items.Insert(0, view.ListViewItem); } } } finally { this.Cursor = Cursors.Default; entryList.EndUpdate(); } }
/// <summary>Counts the system log events of required type</summary> /// <param name="value">the type of log event (Error, Event, Information etc)</param> /// <returns> /// Returns the number of System log entries of specified type /// </returns> public int GetSpecificEventEntriesCount(EventLogEntryType value) { // TODO : Implement GetSpecificEventEntriesCount EventLogEntryCollection systemEvents = (new EventLog("System", ".")).Entries; return(systemEvents.Cast <EventLogEntry>().Count(x => x.EntryType == value)); }
public List <EventLogEntry> getWarnEventLog(string eventType) { List <EventLogEntry> eventLogList = new List <EventLogEntry>(); EventLog MySystemEvent = new EventLog(); //日志对象 MySystemEvent.Log = eventType.ToString(); //日志类型 EventLogEntryCollection MyEventCollection = MySystemEvent.Entries; //获得日志的记录集合 try { int Count = MyEventCollection.Count; //记录的长度 for (int i = 0; i < Count; i++) { EventLogEntry MyEntry = MyEventCollection[Count - i - 1]; if (MyEntry.EntryType == EventLogEntryType.Warning) { if (MyEntry.TimeGenerated.Date == DateTime.Today) //只发送当日的警报 { eventLogList.Add(MyEntry); } } } } catch { } return(eventLogList); }
private List <EventLogEntryDuplicate> MapSystemEventLogEntries(EventLogEntryCollection entries) { List <EventLogEntryDuplicate> eventLogEntryDuplicates = new List <EventLogEntryDuplicate>(); var enumarator = entries.GetEnumerator(); while (enumarator.MoveNext()) { EventLogEntry eventLogEntry = (EventLogEntry)enumarator.Current; eventLogEntryDuplicates.Add(new EventLogEntryDuplicate() { Category = eventLogEntry.Category, //Data = eventLogEntry.Data, CategoryNumber = eventLogEntry.CategoryNumber, EntryType = (EventLogEntryTypeDuplicate)eventLogEntry.EntryType, //Index = eventLogEntry.Index, //InstanceId = eventLogEntry.InstanceId, //MachineName = eventLogEntry.MachineName, Message = eventLogEntry.Message, //ReplacementStrings = eventLogEntry.ReplacementStrings, Source = eventLogEntry.Source, TimeGenerated = eventLogEntry.TimeGenerated, //TimeWritten = eventLogEntry.TimeWritten, UserName = eventLogEntry.UserName, }); } return(eventLogEntryDuplicates); }
public string Execute(string[] args, out bool result) { try { ConfigParse appConfig = new ConfigParse(); EventLog log = new EventLog("MyLogFile1"); EventLogEntryCollection entries = log.Entries; List <MessageRecievedEventArgs> logEntries = new List <MessageRecievedEventArgs>(); foreach (EventLogEntry entry in entries) { Console.Write("add entry log"); logEntries.Add(new MessageRecievedEventArgs( MessageRecievedEventArgs.toMessageTypeEnum(entry.EntryType), entry.Message)); } List <MessageRecievedEventArgs> argsLog = logEntries; string argsJson = JsonConvert.SerializeObject(argsLog); DataInfo inf = new DataInfo(CommandEnum.LogCommand, argsJson); string infJson = JsonConvert.SerializeObject(inf); result = true; return(infJson); } catch (Exception e) { result = false; Debug.WriteLine(e.Message); return(null); } }
public void IncompleteErrorTest() { //Arrange Logger logger = new Logger(); string message = "test error message"; Boolean success = false; string testLogName = EventLog.LogNameFromSourceName("Cloud Foundry Helion Visual Studio Extension", "."); EventLog testLog = new EventLog(); testLog.Log = testLogName; EventLogEntryCollection testLogEntryCollection = testLog.Entries; //Act Logger.Error(message); for (int i = 0; i < testLogEntryCollection.Count; i++) { if (testLogEntryCollection[i].Message == message) { success = true; } } //Assert Assert.IsTrue(success); }
static void Main(string[] args) { string today = DateTime.Now.ToShortDateString(); // 2019-09-01 string logType = "Application"; string logDate = string.Empty; EventLog windowEvent = new EventLog(logType); EventLogEntryCollection entries = windowEvent.Entries; int index = entries.Count - 1; Console.WriteLine(index); while (index > 0) { logDate = entries[index].TimeGenerated.ToShortDateString(); if (logDate.Equals(today)) { if (entries[index].EntryType == EventLogEntryType.Error) { Console.WriteLine("EntryType: {0}", entries[index].EntryType); Console.WriteLine("Message: {0}", entries[index].Message); Console.WriteLine("TimeGenerated: {0}", entries[index].TimeGenerated); Console.WriteLine("============================================"); } } else { break; } index--; } }
public EventsLog() { EventLog sample = new EventLog(); EventLogEntryCollection myCollection = sample.Entries; foreach (EventLogEntry ele in myCollection) { EventLogTraceListener e = new EventLogTraceListener(); Console.WriteLine("Category:" + ele.Category); Console.WriteLine("CategoryNumber:" + ele.CategoryNumber); Console.WriteLine("Data:" + Encoding.Default.GetString(ele.Data)); Console.WriteLine("EntryType:" + ele.EntryType); Console.WriteLine("Message:" + ele.Message); Console.WriteLine("Source:" + ele.Source); Console.WriteLine("InstanceId:" + ele.InstanceId); Console.WriteLine("MachineName:" + ele.MachineName); Console.WriteLine("Source:" + ele.Source); Console.WriteLine("TimeGenerated:" + ele.TimeGenerated); Console.WriteLine("UserName:" + ele.UserName); Console.WriteLine(); Console.WriteLine(); Console.WriteLine(); } }
public string QueryPCOperationTime() { EventLog eventlog = new EventLog(); //"Application"应用程序, "Security"安全, "System"系统 eventlog.Log = "System"; EventLogEntryCollection elec = eventlog.Entries; StringBuilder sb = new StringBuilder(); foreach (EventLogEntry entry in elec) { if (entry.InstanceId == 12) { sb.AppendFormat("Date={0}, Time of Reboot={1};", entry.TimeGenerated.ToLongDateString(), entry.TimeGenerated.ToLongTimeString()); sb.AppendLine(); } if (entry.InstanceId == 13) { sb.AppendFormat("Date={0}, Time of Shutdown={1};", entry.TimeGenerated.ToLongDateString(), entry.TimeGenerated.ToLongTimeString()); sb.AppendLine(); } } return(sb.ToString()); }
private static void CheckEventLogOnMachine( string eventLogName, string[] sourceNames, TimeSpan lookBackInterval, StringBuilder matchedEntries, string machineName) { int matchCount = 1; EventLog eventLog = new EventLog(eventLogName, machineName); EventLogEntryCollection logEntries = eventLog.Entries; int count = logEntries.Count; for (int i = 0; i < count; i++) { EventLogEntry entry = logEntries[i]; if (entry.EntryType == EventLogEntryType.Error || entry.EntryType == EventLogEntryType.Warning) { if ((DateTime.Now - entry.TimeGenerated) < lookBackInterval) { for (int j = 0; j < sourceNames.Length; j++) { string source = entry.Source; if (source.Equals(sourceNames[j])) { matchedEntries.Append(string.Format("Machine {0} Match {1}: {2}\n", machineName, matchCount++, entry.Message)); } } } } } }
private void toolStripButton1_Click(object sender, EventArgs e) { string sourceName = "EventLoggingApp"; string machineName = "arefev"; String myEventType = null; EventLog myEventLog = new EventLog("Application"); myEventLog.Source = sourceName; myEventLog.MachineName = machineName; EventLogEntryCollection myLogEntryCollection = myEventLog.Entries; int myCount = myLogEntryCollection.Count; // Iterate through all 'EventLogEntry' instances in 'EventLog'. for (int i = myCount - 1; i > 0; i--) { EventLogEntry myLogEntry = myLogEntryCollection[i]; // Select the entry having desired EventType. if (myLogEntry.EntryType.ToString().Equals(myEventType)) { // Display Source of the event. eventLogTable.Rows.Add(myLogEntry.Message); return; } } }
public void getWindowsErrorLog() { this.BeginInvoke((Action)(() => { textBox2.Text = ""; })); EventLog eventlog = new EventLog(); eventlog.Log = "Application"; List <Hashtable> logs = new List <Hashtable>(); //"Application"应用程序, "Security"安全, "System"系统 EventLogEntryCollection eventLogEntryCollection = eventlog.Entries; foreach (EventLogEntry entry in eventLogEntryCollection) { if (@"Apache Service" == entry.Source.ToString() || @"MySQL" == entry.Source.ToString()) { string t = entry.TimeGenerated.ToLongDateString() + " " + entry.TimeGenerated.ToLongTimeString(); Hashtable hashtable = new Hashtable(); if (entry.EntryType.ToString().Equals("Error")) { hashtable.Add("Source", entry.Source.ToString()); hashtable.Add("time", t); hashtable.Add("msg", entry.Message.ToString()); logs.Add(hashtable); } } } logs.Reverse(); int i = 0; foreach (Hashtable hashtable1 in logs) { if (i <= 100) { this.BeginInvoke((Action)(() => { string date = hashtable1["time"].ToString(); string log = @"-------------" + hashtable1["Source"].ToString() + @" Error Log---------------- 时间:" + date + @" 日志: " + hashtable1["msg"].ToString() + @" "; textBox2.AppendText(log); //textBox2.AppendText(Environment.NewLine); textBox2.ScrollToCaret(); })); i++; } } }
private void printErrors() { //string path = Environment.CurrentDirectory + @"\systemlog.txt"; string path2 = Environment.CurrentDirectory + @"\systemlog.html"; // Console.WriteLine(path); // StreamWriter file = new StreamWriter(path, false); StreamWriter file2 = new StreamWriter(path2, false); file2.Flush(); // EventLog[] log = EventLog.GetEventLogs(); // Looks in the system log file EventLog myE = new EventLog("System", "."); // foreach (EventLog aLog in log) //{ //Console.WriteLine("Log name: "+aLog.Log); //Console.WriteLine("Number of event log entries: "+aLog.Entries.Count.ToString()); // } EventLogEntryCollection col = myE.Entries; //file2.WriteLine("<html><head><meta http-equiv=\"Content - Type\" content=\"text / html; charset = UTF - 8\"/></head><body bgcolor =#000000 leftmargin=2 topmargin=2 bottommargin=2 rightmargin=2>"); for (int i = 0; i < col.Count; i++) { EventLogEntry entry = col[i]; if (whatErr == "All") { // OPTIONS "Error", "Critical", "Warning", "Information" // https://msdn.microsoft.com/en-us/library/system.diagnostics.eventlogentry(v=vs.90).aspx if (entry.EntryType.ToString().Equals("Error")) { // Console.WriteLine("Source: "+entry.Source+", id: "+entry.EventID+" date: "+entry.TimeGenerated); //file.WriteLine("Source: " + entry.Source + ", id: " + entry.EventID + " date: " + entry.TimeGenerated); // + ", message: " + entry.Message); file2.WriteLine("<table bgcolor =#000000 border=0 cellpadding=0 cellspacing=8 width=100%><tr><td width=130 align=left valign=middle><font color=#FFFFFF style=\"font-family: arial; font-size: 12px;\" >" + entry.TimeGenerated + "</font></td><td align=left valign=middle width=5 style=\"background-color: #C6DC00;\"></td><td align=left valign=middle><font color=#C6DC00 style=\"font-family: arial; font-size: 10px; font-weight: bold;\">" + "Error: " + entry.EventID + "<br></font><font color=#C4C4C4 style=\"font-family: arial; font-size: 12px; font-weight: normal;\"><p>Source: " + entry.Source + "</br>Message: " + entry.Message + "</p></font></td></tr></table><table border=0 cellpadding=0 cellspacing=0 height=1 width=100% bgcolor=#262626><tr><td></td></tr></table>"); } if (entry.EntryType.ToString().Equals("Critical")) { file2.WriteLine("<table bgcolor =#000000 border=0 cellpadding=0 cellspacing=8 width=100%><tr><td width=130 align=left valign=middle><font color=#FFFFFF style=\"font-family: arial; font-size: 12px;\" >" + entry.TimeGenerated + "</font></td><td align=left valign=middle width=5 style=\"background-color: #DC1600;\"></td><td align=left valign=middle><font color=#DC1600 style=\"font-family: arial; font-size: 10px; font-weight: bold;\">" + "Critical: " + entry.EventID + "<br></font><font color=#C4C4C4 style=\"font-family: arial; font-size: 12px; font-weight: normal;\">Source: " + entry.Source + "</br>Message: " + entry.Message + "</p></font></td></tr></table><table border=0 cellpadding=0 cellspacing=0 height=1 width=100% bgcolor=#262626><tr><td></td></tr></table>"); } } else if (whatErr == "Error") { if (entry.EntryType.ToString().Equals("Error")) { // Console.WriteLine("Source: "+entry.Source+", id: "+entry.EventID+" date: "+entry.TimeGenerated); //file.WriteLine("Source: " + entry.Source + ", id: " + entry.EventID + " date: " + entry.TimeGenerated); // + ", message: " + entry.Message); file2.WriteLine("<table bgcolor =#000000 border=0 cellpadding=0 cellspacing=8 width=100%><tr><td width=130 align=left valign=middle><font color=#FFFFFF style=\"font-family: arial; font-size: 12px;\" >" + entry.TimeGenerated + "</font></td><td align=left valign=middle width=5 style=\"background-color: #C6DC00;\"></td><td align=left valign=middle><font color=#C6DC00 style=\"font-family: arial; font-size: 10px; font-weight: bold;\">" + "Error: " + entry.EventID + "<br></font><font color=#C4C4C4 style=\"font-family: arial; font-size: 12px; font-weight: normal;\"><p>Source: " + entry.Source + "</br>Message: " + entry.Message + "</p></font></td></tr></table><table border=0 cellpadding=0 cellspacing=0 height=1 width=100% bgcolor=#262626><tr><td></td></tr></table>"); } } else { if (entry.EntryType.ToString().Equals("Critical")) { file2.WriteLine("<table bgcolor =#000000 border=0 cellpadding=0 cellspacing=8 width=100%><tr><td width=130 align=left valign=middle><font color=#FFFFFF style=\"font-family: arial; font-size: 12px;\" >" + entry.TimeGenerated + "</font></td><td align=left valign=middle width=5 style=\"background-color: #DC1600;\"></td><td align=left valign=middle><font color=#DC1600 style=\"font-family: arial; font-size: 10px; font-weight: bold;\">" + "Critical: " + entry.EventID + "<br></font><font color=#C4C4C4 style=\"font-family: arial; font-size: 12px; font-weight: normal;\"><p>Source: " + entry.Source + "</br>Message: " + entry.Message + "</p></font></td></tr></table><table border=0 cellpadding=0 cellspacing=0 height=1 width=100% bgcolor=#262626><tr><td></td></tr></table>"); } } } //file2.WriteLine("</ body ></ html >"); file2.Close(); // http://stackoverflow.com/questions/12735897/streamwriter-is-cutting-off-my-last-couple-of-lines-sometimes-in-the-middle-of-a }
/// <summary>Counts the system log events of required type</summary> /// <param name="value">the type of log event (Error, Event, Information etc)</param> /// <returns> /// Returns the number of System log entries of specified type /// </returns> public int GetSpecificEventEntriesCount(EventLogEntryType value) { EventLogEntryCollection systemEvents = (new EventLog("System", ".")).Entries; return(systemEvents .OfType <EventLogEntry>() .Count(e => e.EntryType == value)); }
/// <summary>Counts the system log events of required type</summary> /// <param name="value">the type of log event (Error, Event, Information etc)</param> /// <returns> /// Returns the number of System log entries of specified type /// </returns> public int GetSpecificEventEntriesCount(EventLogEntryType value) { // TODO : Implement GetSpecificEventEntriesCount EventLogEntryCollection systemEvents = (new EventLog("System", ".")).Entries; //return systemEvents.Cast<EventLogEntry>().Where(x => x.EntryType == value).Count(); throw new NotImplementedException(); }
/// <summary> /// Prints all. /// </summary> /// <param name="myEventLogEntryCollection">My event log entry collection.</param> private static void PrintAll(EventLogEntryCollection myEventLogEntryCollection) { for (int i = 0; i < myEventLogEntryCollection.Count; i++) { Console.WriteLine("The Message of the EventLog is :" + myEventLogEntryCollection[i].Message); } }
/// <summary> /// Loads the log entries from the active log file. /// </summary> /// <returns> /// A collection of the entries contained within the active log file. /// </returns> private static EventLogEntryCollection LoadActiveLog( ) { // Load the active log file string path = Path.Combine(SpecialFolder.GetSpecialFolderPath(SpecialMachineFolders.Log), "Log.xml"); EventLogEntryCollection eventLogEntries = LoadLog(path); return(eventLogEntries); }
/// <summary>Counts the system log events of required type</summary> /// <param name="value">the type of log event (Error, Event, Information etc)</param> /// <returns> /// Returns the number of System log entries of specified type /// </returns> public int GetSpecificEventEntriesCount(EventLogEntryType value) { // TODO : Implement GetSpecificEventEntriesCount //throw new NotImplementedException(); EventLogEntryCollection systemEvents = (new EventLog("System", ".")).Entries; return(systemEvents.OfType <EventLogEntry>().Count(x => x.EntryType == value)); }
private DataTable PopulateEventLogEntries(EventLogEntryCollection logCollection) { DataTable dt = new DataTable(); // define the table's schema dt.Columns.Add(new DataColumn("EventID", typeof(string))); dt.Columns.Add(new DataColumn("EntryType", typeof(string))); dt.Columns.Add(new DataColumn("Source", typeof(string))); dt.Columns.Add(new DataColumn("DateTime", typeof(DateTime))); dt.Columns.Add(new DataColumn("Message", typeof(string))); DataRow dr = null; foreach (EventLogEntry entry in logCollection) { dr = dt.NewRow(); dr[0] = entry.InstanceId; dr[1] = entry.EntryType; dr[2] = entry.Source; dr[3] = entry.TimeGenerated; dr[4] = entry.Message; dt.Rows.Add(dr); } return dt; }
public void Clear() { //Clear all the log items from the xml int y = this.nodeLog.ChildNodes.Count; for(int x = 0; x<y;x++) this.nodeLog.RemoveChild(this.nodeLog.ChildNodes[0]); //Save the xml file this.SaveLogFile(); //Re-init the eventLogCollection this.eventLogEntryCollection = new EventLogEntryCollection(); }
/// <summary> /// Loads the eventlog entry collection /// </summary> private void LoadEventLogEntryCollection() { //This is only called when the log is changed and when the class is instantiated so it's pretty safe //to re-init the collection this.eventLogEntryCollection = new EventLogEntryCollection(); string[] attributes = new string[]{"machineName","userName","timeGenerated", "source","message","eventLogEntryType", "eventID","category","rawData","id","timeWritten","index"}; //Get all the eventLog nodes foreach(XmlNode node in this.nodeLog.ChildNodes) { string machineName = node.Attributes.GetNamedItem(attributes[0]).Value; string userName = node.Attributes.GetNamedItem(attributes[1]).Value; DateTime timeGenerated = DateTime.Parse(node.Attributes.GetNamedItem(attributes[2]).Value); string source = node.Attributes.GetNamedItem(attributes[3]).Value; string message = node.Attributes.GetNamedItem(attributes[4]).Value; EventLogEntryType type = (EventLogEntryType)Int32.Parse(node.Attributes.GetNamedItem(attributes[5]).Value); int eventID = Int32.Parse(node.Attributes.GetNamedItem(attributes[6]).Value); short category = Int16.Parse(node.Attributes.GetNamedItem(attributes[7]).Value); string srawData = node.Attributes.GetNamedItem(attributes[8]).Value; byte[] rawData = new byte[0]; if(srawData.Length > 0) rawData = Convert.FromBase64String(srawData); string id = node.Attributes.GetNamedItem(attributes[9]).Value; DateTime timeWritten = DateTime.Parse(node.Attributes.GetNamedItem(attributes[10]).Value); int index = Int32.Parse(node.Attributes.GetNamedItem(attributes[11]).Value); //Add to the collection EventLogEntry eventLogEntry = new EventLogEntry(category,rawData,type,eventID,index,machineName,message,source,timeGenerated,timeWritten,userName,id); this.eventLogEntryCollection.Add(eventLogEntry); } }
public void Close() { this.SaveLogFile(); this.nodeLog = null; this.log = ""; this.source =""; this.logDisplayName = ""; this.eventLogEntryCollection = new EventLogEntryCollection(); }