简体   繁体   中英

Read event log in C#

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);
    }
}

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();

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.

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)

I am not really sure what you were trying to print on the console. If it is the in each event log entry that you are trying to print, inside the foreach loop you should have this instead: ,则在foreach循环内应该改为:

Console.WriteLine(log.Message + "\n");

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM