Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

win32evtlogutil.py 7.4KB

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