Skip to content

Instantly share code, notes, and snippets.

@inokappa
Last active August 29, 2017 13:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inokappa/c000450f4b45881f73d2 to your computer and use it in GitHub Desktop.
Save inokappa/c000450f4b45881f73d2 to your computer and use it in GitHub Desktop.
Python スクリプトから Windows Server のイベントログにログを送るメモ
# -*- coding:utf-8 -*-
import win32api
import win32con
import win32evtlog
import win32security
import win32evtlogutil
import time
class EventLog:
def __init__(self):
'''
- SID の生成
- refer to http://www.atmarkit.co.jp/ait/articles/0306/28/news004.html
'''
self.ph = win32api.GetCurrentProcess()
self.th = win32security.OpenProcessToken(self.ph, win32con.TOKEN_READ)
self.sid = win32security.GetTokenInformation(self.th, win32security.TokenUser)[0]
'''
- イベントログの共通情報
- appName = アプリケーション名を指定
- data = LogName を指定
'''
self.appName = "o-re-no-Application"
self.data = "Application\0Data".encode("ascii")
'''
- EventLog.info
- eventID = 任意のイベント ID を指定(0 ~ 65535 を指定可能)
- type = win32evtlog の EVENTLOG_INFORMATION_TYPE を指定
'''
def info(self, message):
eventID = 65500
type = win32evtlog.EVENTLOG_INFORMATION_TYPE
desc = [message]
self.write_event_log(eventID, type, desc)
'''
- EventLog.warn
- eventID = 任意のイベント ID を指定(0 ~ 65535 を指定可能)
- type = win32evtlog の EVENTLOG_WARNING_TYPE を指定
'''
def warn(self, message):
eventID = 65501
type = win32evtlog.EVENTLOG_WARNING_TYPE
desc = [message]
self.write_event_log(eventID, type, desc)
'''
- EventLog.warn
- eventID = 任意のイベント ID を指定(0 ~ 65535 を指定可能)
- type = win32evtlog の EVENTLOG_ERROR_TYPE を指定
'''
def crit(self, message):
eventID = 65502
type = win32evtlog.EVENTLOG_ERROR_TYPE
desc = [message]
self.write_event_log(eventID, type, desc)
'''
- イベントログへの書き込み
- win32evtlogutil の ReportEvent メソッドを利用
'''
def write_event_log(self, eventID, type, desc):
win32evtlogutil.ReportEvent(
self.appName,
eventID,
eventType=type,
strings=desc,
data=self.data,
sid=self.sid
)
class OrenoSvc:
def main(self):
eventlog = EventLog()
eventlog.info('Starting Oreno Service ...')
try:
while True:
time.sleep(5)
eventlog.info("Komanechi!! at %s" % time.ctime())
except KeyboardInterrupt:
eventlog.warn('stop signal was received : Stopping loop ...')
if __name__ == '__main__':
ore = OrenoSvc()
ore.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment