Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read Event Log Remotely with .NET

I want to read the Event Log on a remote computer to check for errors during testing. Here's some relevant code:

public bool CheckEventLogs(DateTime start)
{
  EventLog myEventLog = new EventLog("CustomLog", "ServerName");
  bool errorFound = false;
  foreach (EventLogEntry entry in myEventLog.Entries)
  {
    if (entry.EntryType == EventLogEntryType.Error && entry.TimeGenerated >= start)
    {
       Console.WriteLine("Error in Event Log:\n" + entry.Message + "\n");
       errorFound = true;
    }
  }
  return errorFound;
}

Currently, this code throws an exception (Attempted to perform an unauthorized operation). According to MSDN, I need EventLogPermission, but I have been struggling to find any examples of how to use this permission. Does anyone have an example of how to do this?

Edit: Response to Comments

Thank you all for the comments - here is the additional information requested:

The exception is thrown from the foreach statement. Specifically, when stepping through the code it thrown in the step after when in is highlighted. It seems that I was able to create the event log object but I'm not able to access the entries in the event log.

My account does not have permission to read the event log on the target system, but I have credentials for an account which does. When connecting manually through the event viewer there is an option to connect as another user. After doing this manually, then my code ran without a problem. However, I cannot rely doing it manually every time this program runs. What I need is a way to connect as another user programmaticly. I thought that the EventLogPermission would be the way to do that, but maybe there is another way. If anyone knows how to connect to a remote log as a different user in C#, that would be exactly what I was looking for.

like image 664
Brian Avatar asked Mar 15 '11 14:03

Brian


1 Answers

WMI is incredibly useful for this, a snippet like

SELECT Logfile,TimeGenerated,Type,SourceName,Message FROM Win32_NTLogEvent

Would allow you to query the logs. This utility from MS will allow you to explore WMI and will even build the .net code to invoke the queries.

Another benefit to this is that its going to get all the events and bring them local to the application where you can parse them at your leisure. Iterating the events in the way you are doing now is prone to failure if the connection is broken while you are processing (incidentally this is the same method that is typically employed with database access).

like image 100
StingyJack Avatar answered Sep 26 '22 00:09

StingyJack