简体   繁体   中英

How to enumerate all the registered sources for an EventLog

If I select to filter the "Application" log in the EventLog viewer, I can see a lot of Sources registered with the "Application" log. How could I programmatically enumerate all these sources via C#? And it seems I cannot register my own evento source with "Application" and "System" log, why?

BTW: The concept of "event source" is really confusing...

There might be a more appropriate .NET or Windows API you could reference for this, but the info is ultimately stored in the registry under the Eventlog service key. The service's root key is here: HKLM\\SYSTEM\\CurrentControlSet\\Services\\Eventlog

Most of the subkeys under that key will be the various event logs on the system including System and Application . For each log, it will contain a bunch of additional subkeys that represent the registered sources for that log. So just enumerate the subkeys to get your list.

On XP/2003 OSes, the log's subkey also contains a REG_MULTI_SZ value called Sources that should match the list of source subkeys. That value appears to no longer be used on Win7/2008 R2 machines (not sure about Vista).

Here is a code snippet to enum the sources. Note:

  • Each SourceName must be unique per machine, NOT per log. (Thats why I didnt use SourceName like a sub class of EventLog)
  • You need admin privilges to enum logs. Use in Settings / Windows-Settings:
    <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3"> <requestedExecutionLevel level="requireAdministrator" uiAccess="false" /> </requestedPrivileges>
  • If you create a new source you must wait a while until it is registered at system
  • If you switch a source to another log, you must restart between deleting and (re-)creating source.

Imports System.Diagnostics
Imports  Microsoft.Win32

Public Class ClsEventSources

Friend Class MySourcesInfo
  Friend LogName As String
  Friend SourceName As String
End Class

Private MyEventLogList As New List(Of EventLog)
Private MySourceList As New List(Of MySourcesInfo)

Private Const RegEventLogPath As String = "SYSTEM\CurrentControlSet\Services\Eventlog\"

  Private Sub New()

    MyEventLogList = EventLog.GetEventLogs.ToList

    For Each Ev In MyEventLogList 

        For Each SubKeyName In _
           Registry.LocalMachine.OpenSubKey(RegEventLogPath & _
                                  Ev.Log).GetSubKeyNames

            MySourceList.Add(New MySourcesInfo With _
                      {.LogName = Ev.Log, .SourceName = SubKeyName})
        Next     

    Next

  End Sub

End Class

查看System.Diagnostics.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