Alex Zhukovskiy
Alex Zhukovskiy

Reputation: 10035

Cannot read event log due to SecurityException

I'm writing a little dll for my webapp. I'm monitoring a service i have a webpage that shows if a service is running, stopped or something other. So i'd like to get last 10 entries of EventLog logged by this service. But when i'm doing i get an exception while calling ToArray(). What should I do?

    public static IEnumerable<EventLogEntry> GetEventLogs(string serviceName)
    {
        if (!EventLog.SourceExists(serviceName))
            throw new ArgumentException("Service not found", "serviceName");
        var myLog = new EventLog { Source = "MySource" };

        var entries = myLog.Entries;
        return (from EventLogEntry entry in entries
                where entry.Source == serviceName
                select entry).ToArray();
    }

So EventLog.SourceExists(serviceName) returns true, but after it fails.

It fails while iterating through Security folder, but i need Application only



Solved

It's funny that i can read from specified folder, however. It depends on Log property of EventLog class. So i should simple replace one row by this

var myLog = new EventLog {Source = "MySource", Log = "Application"};

Another joke is it works sometimes. And sometimes doesn't. For example this code works for my services, but fails with netprofm service. tnx for help everybody

Upvotes: 2

Views: 2057

Answers (1)

tnw
tnw

Reputation: 13887

You need to have admin privileges to read from the Event Log. Are you running as the administrator?

You can also modify the permissions to this in the registry:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\Security

Right click on that entry, select permissions, and make sure you have access.

You can't just skip the Security folder and look in Application only. From the documentation:

To search for an event source in Windows Vista and later or Windows Server 2003, you must have administrative privileges. The reason for this requirement is that all event logs, including security, must be searched to determine whether the event source is unique. Starting with Windows Vista, users do not have permission to access the security log; therefore, a SecurityException is thrown.

Further reading and another relevant quote:

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.

Upvotes: 4

Related Questions