Search code examples
windowspython-3.xeventsevent-logpywin32

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?


Solution

  • 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: