Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing to Windows Event Log using win32evtlog from pywin32 library

I have a simple python script that will be running on a windows server, I'd like to log specific events throughout the script to the windows event log. Does anyone have a simple and precise example of writing to the windows event log so I can view the event from the event viewer. I've read through the docs for the pywin32 library and I can't find any clear examples. I've tried building an event using:

win32evtlogutil.ReportEvent(ApplicationName, EventID, EventCategory,
                EventType, Inserts, Data, SID)

I've had no success, could someone explain the ReportEvent a bit more in depth?

like image 257
Rights Avatar asked Jan 20 '26 14:01

Rights


1 Answers

A simple example:

>>> import sys
>>> import time
>>>
>>> import win32evtlog
>>> import win32evtlogutil
>>>
>>>
>>> "Python {:s} on {:s}".format(sys.version, sys.platform)
'Python 3.5.4 (v3.5.4:3f56838, Aug  8 2017, 02:17:05) [MSC v.1900 64 bit (AMD64)] on win32'
>>>
>>> DUMMY_EVT_APP_NAME = "Dummy Application"
>>> DUMMY_EVT_ID = 7040  # Got this from another event
>>> DUMMY_EVT_CATEG = 9876
>>> DUMMY_EVT_STRS = ["Dummy event string {:d}".format(item) for item in range(5)]
>>> DUMMY_EVT_DATA = b"Dummy event data"
>>>
>>> "Current time: {:s}".format(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
'Current time: 2018-07-18 20:03:08'
>>>
>>> win32evtlogutil.ReportEvent(
...     DUMMY_EVT_APP_NAME, DUMMY_EVT_ID, eventCategory=DUMMY_EVT_CATEG,
...     eventType=win32evtlog.EVENTLOG_WARNING_TYPE, strings=DUMMY_EVT_STRS,
...     data=DUMMY_EVT_DATA)
>>>

Output:

Event Viewer

You can see the correspondence between the values that I input from code, and the event fields in the (above) image of the Event Viewer (MMC) window.

win32evtlogutil.ReportEvent is part of [GitHub]: mhammond/pywin32 - Python for Windows (pywin32) Extensions, which is a Python wrapper over WinAPIs.
Documentation (WiP) can be found at [GitHub.MHammond]: Python for Win32 Extensions Help (or [ME.TimGolden]: Python for Win32 Extensions Help).

Everything you need to know is explained at [MS.Learn]: ReportEventW function (winbase.h), which is the WinAPI used to accomplish this task. Make sure to read it carefully (and some other URLs that it references) in order to get more familiar about the arguments, what their values could be, and other info.

Make sure not to abuse (tests included), or you might end up getting the event log polluted with lots of garbage data.

Might also be interesting to read:

  • [SO]: Converting Python win32evtlog objects to xml (@CristiFati's answer)
like image 180
CristiFati Avatar answered Jan 23 '26 14:01

CristiFati



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!