win32evtlogutil.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. """Event Log Utilities - helper for win32evtlog.pyd
  2. """
  3. import win32api, win32con, winerror, win32evtlog
  4. error = win32api.error # The error the evtlog module raises.
  5. langid = win32api.MAKELANGID(win32con.LANG_NEUTRAL, win32con.SUBLANG_NEUTRAL)
  6. def AddSourceToRegistry(appName, msgDLL = None, eventLogType = "Application", eventLogFlags = None):
  7. """Add a source of messages to the event log.
  8. Allows Python program to register a custom source of messages in the
  9. registry. You must also provide the DLL name that has the message table, so the
  10. full message text appears in the event log.
  11. Note that the win32evtlog.pyd file has a number of string entries with just "%1"
  12. built in, so many Python programs can simply use this DLL. Disadvantages are that
  13. you do not get language translation, and the full text is stored in the event log,
  14. blowing the size of the log up.
  15. """
  16. # When an application uses the RegisterEventSource or OpenEventLog
  17. # function to get a handle of an event log, the event loggging service
  18. # searches for the specified source name in the registry. You can add a
  19. # new source name to the registry by opening a new registry subkey
  20. # under the Application key and adding registry values to the new
  21. # subkey.
  22. if msgDLL is None:
  23. msgDLL = win32evtlog.__file__
  24. # Create a new key for our application
  25. hkey = win32api.RegCreateKey(win32con.HKEY_LOCAL_MACHINE, \
  26. "SYSTEM\\CurrentControlSet\\Services\\EventLog\\%s\\%s" % (eventLogType, appName))
  27. # Add the Event-ID message-file name to the subkey.
  28. win32api.RegSetValueEx(hkey,
  29. "EventMessageFile", # value name \
  30. 0, # reserved \
  31. win32con.REG_EXPAND_SZ,# value type \
  32. msgDLL)
  33. # Set the supported types flags and add it to the subkey.
  34. if eventLogFlags is None:
  35. eventLogFlags = win32evtlog.EVENTLOG_ERROR_TYPE | win32evtlog.EVENTLOG_WARNING_TYPE | win32evtlog.EVENTLOG_INFORMATION_TYPE
  36. win32api.RegSetValueEx(hkey, # subkey handle \
  37. "TypesSupported", # value name \
  38. 0, # reserved \
  39. win32con.REG_DWORD, # value type \
  40. eventLogFlags)
  41. win32api.RegCloseKey(hkey)
  42. def RemoveSourceFromRegistry(appName, eventLogType = "Application"):
  43. """Removes a source of messages from the event log.
  44. """
  45. # Delete our key
  46. try:
  47. win32api.RegDeleteKey(win32con.HKEY_LOCAL_MACHINE, \
  48. "SYSTEM\\CurrentControlSet\\Services\\EventLog\\%s\\%s" % (eventLogType, appName))
  49. except win32api.error as exc:
  50. if exc.winerror != winerror.ERROR_FILE_NOT_FOUND:
  51. raise
  52. def ReportEvent(appName, eventID, eventCategory = 0, eventType=win32evtlog.EVENTLOG_ERROR_TYPE, strings = None, data = None, sid=None):
  53. """Report an event for a previously added event source.
  54. """
  55. # Get a handle to the Application event log
  56. hAppLog = win32evtlog.RegisterEventSource(None, appName)
  57. # Now report the event, which will add this event to the event log */
  58. win32evtlog.ReportEvent(hAppLog, # event-log handle \
  59. eventType,
  60. eventCategory,
  61. eventID,
  62. sid,
  63. strings,
  64. data)
  65. win32evtlog.DeregisterEventSource(hAppLog);
  66. def FormatMessage( eventLogRecord, logType="Application" ):
  67. """Given a tuple from ReadEventLog, and optionally where the event
  68. record came from, load the message, and process message inserts.
  69. Note that this function may raise win32api.error. See also the
  70. function SafeFormatMessage which will return None if the message can
  71. not be processed.
  72. """
  73. # From the event log source name, we know the name of the registry
  74. # key to look under for the name of the message DLL that contains
  75. # the messages we need to extract with FormatMessage. So first get
  76. # the event log source name...
  77. keyName = "SYSTEM\\CurrentControlSet\\Services\\EventLog\\%s\\%s" % (logType, eventLogRecord.SourceName)
  78. # Now open this key and get the EventMessageFile value, which is
  79. # the name of the message DLL.
  80. handle = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, keyName)
  81. try:
  82. dllNames = win32api.RegQueryValueEx(handle, "EventMessageFile")[0].split(";")
  83. # Win2k etc appear to allow multiple DLL names
  84. data = None
  85. for dllName in dllNames:
  86. try:
  87. # Expand environment variable strings in the message DLL path name,
  88. # in case any are there.
  89. dllName = win32api.ExpandEnvironmentStrings(dllName)
  90. dllHandle = win32api.LoadLibraryEx(dllName, 0, win32con.LOAD_LIBRARY_AS_DATAFILE)
  91. try:
  92. data = win32api.FormatMessageW(win32con.FORMAT_MESSAGE_FROM_HMODULE,
  93. dllHandle, eventLogRecord.EventID, langid, eventLogRecord.StringInserts)
  94. finally:
  95. win32api.FreeLibrary(dllHandle)
  96. except win32api.error:
  97. pass # Not in this DLL - try the next
  98. if data is not None:
  99. break
  100. finally:
  101. win32api.RegCloseKey(handle)
  102. return data or '' # Don't want "None" ever being returned.
  103. def SafeFormatMessage( eventLogRecord, logType=None ):
  104. """As for FormatMessage, except returns an error message if
  105. the message can not be processed.
  106. """
  107. if logType is None: logType = "Application"
  108. try:
  109. return FormatMessage(eventLogRecord, logType)
  110. except win32api.error:
  111. if eventLogRecord.StringInserts is None:
  112. desc = ""
  113. else:
  114. desc = ", ".join(eventLogRecord.StringInserts)
  115. return "<The description for Event ID ( %d ) in Source ( %r ) could not be found. It contains the following insertion string(s):%r.>" % (winerror.HRESULT_CODE(eventLogRecord.EventID), eventLogRecord.SourceName, desc)
  116. def FeedEventLogRecords(feeder, machineName = None, logName = "Application", readFlags = None):
  117. if readFlags is None:
  118. readFlags = win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ
  119. h=win32evtlog.OpenEventLog(machineName, logName)
  120. try:
  121. while 1:
  122. objects = win32evtlog.ReadEventLog(h, readFlags, 0)
  123. if not objects:
  124. break
  125. map(lambda item, feeder = feeder: feeder(*(item,)), objects)
  126. finally:
  127. win32evtlog.CloseEventLog(h)