ログの出力先としてイベントログを指定されることもあるため、いつものようにザックリと記載しておこう。他言語でイベントログのお作法を理解していれば、設計での決め事はPythonでも変わらない。関数なりクラスなり用意しておいて使い回すと良いだろう。
開発環境:
Python 3.9.4
参考情報:
まず、Pythonからイベントログへ書き込むために使用するイベントソースを定め、予め作成しよう。このサンプルではApplicationにPyEventというイベントソースを作成した。イベントソースが存在しない状態で書き込みを行うと下図のようなメッセージが出力されてしまう。
イベントソースを作成する際は、いつもPowerShellを使っている。
New-EventLog -LogName Application -Source PyEvent
もちろん、「管理者として実行」しないとアクセス拒否される。エラーは下図のようなものだ。
正常終了は何も出力されない。イベントログの書き込みをしてみよう。まずはPowerShellで確認だ。
Write-EventLog -LogName Application -Source PyEvent -EventID 40001 -EntryType Information -Message 'Write-EventLogのテスト'
下記のコードでイベントログの書き込みを行う。イベントビューアーで確認しよう。
#! coding: SJIS
import win32api
import win32con
import win32evtlog
import win32security
import win32evtlogutil
process_handle = win32api.GetCurrentProcess()
token = win32security.OpenProcessToken(process_handle, win32con.TOKEN_READ)
security_id = win32security.GetTokenInformation(token, win32security.TokenUser)[0]
event_source = "PyEVENT" # 予め用意したイベントソース名に合わせよう
event_id = 65535 # 0-65535の範囲で指定可能だ
category = 0 # カテゴリはint16
event_type = win32evtlog.EVENTLOG_ERROR_TYPE
descr = ['ERROR:テストメッセージ', '詳細:テストメッセージ']
data = "Application\0Data".encode("ascii")
win32evtlogutil.ReportEvent(event_source, event_id, \
eventCategory=category, eventType=event_type, strings=descr, \
data=data, sid=security_id)
補足すると、Typeは下記の選択肢が用意されている。
EVENTLOG_SUCCESS
EVENTLOG_AUDIT_FAILURE
EVENTLOG_AUDIT_SUCCESS
EVENTLOG_ERROR_TYPE
EVENTLOG_INFORMATION_TYPE
EVENTLOG_WARNING_TYPE
下図のようにSyntax Errorに見舞われたら、sample.pyをSJISで保存し直して、ファイルの先頭行に「#! coding: SJIS」を忘れないようにしよう。もちろんUTF-8で統一してもエラー回避可能だ。
Windows OSに配置した場合、心得がない要員が編集する可能性も考慮してSJISにしておいた方が無難ではなかろうか。と、最近感じている。
まとめ:
ひとつの方法論に囚われず、環境に適したアプローチを選択しよう
文字コードは忘れずに