26

I'm trying to read event logs for my application EventLoggingApp. The problem is reading logs for my single source (EventLoggingApp).

This code read logs for every source. What is the problem? Any advice?

static void ReadEvenLog()
{
    string eventLogName = "Application";
    string sourceName = "EventLoggingApp";
    string machineName = "Tom";

    EventLog eventLog = new EventLog();
    eventLog.Log = eventLogName;
    eventLog.Source = sourceName;
    eventLog.MachineName = machineName;

    foreach (EventLogEntry log in eventLog.Entries)
    {
        Console.WriteLine("{0}\n",log.Source);
    }
}
martijnn2008
  • 3,552
  • 5
  • 30
  • 40
Tom159
  • 291
  • 1
  • 3
  • 5

5 Answers5

31

Try this:

EventLog log = new EventLog("Security");
var entries = log.Entries.Cast<EventLogEntry>()
                         .Where(x => x.InstanceId == 4624)
                         .Select(x => new
                         {
                             x.MachineName,
                             x.Site,
                             x.Source,
                             x.Message
                         }).ToList();
martijnn2008
  • 3,552
  • 5
  • 30
  • 40
Domenico
  • 309
  • 3
  • 6
5

Check out this article on MSDN. You can't read event log entries by source. Only log name matters. Instead you can create separate event log for you application or filter entries by verifying Source property of each entry in foreach loop.

1

MSDN (1)(2) says that Source is for writing event logs only.

It is not necessary to specify a Source when only reading from a log. You can specify only the Log name and MachineName (server computer name) properties for the EventLog instance. In either case, the Entries member is automatically populated with the event log's list of entries. You can select the appropriate index for an item in this list to read individual entries. (1)

atamanroman
  • 11,607
  • 7
  • 57
  • 81
0

I am not really sure what you were trying to print on the console. If it is the message in each event log entry that you are trying to print, inside the foreach loop you should have this instead:

Console.WriteLine(log.Message + "\n");
Tanvir
  • 1,453
  • 2
  • 16
  • 32
-1

If you connect to localhost set MachineName to "." Check if user has right to read from eventlog

Aik
  • 3,528
  • 3
  • 19
  • 20