はじめに
ElastAlertのカスタムルールの作成時にデバッグで処理途中の値をコンソールに出力する方法をご紹介します。
Version
ElastAlert 0.2.4
カスタムルール
ここでは、ElastAlert公式のチュートリアルのカスタムルール(正確にはカスタムモジュール)を例とします。
モジュールのインポート
コンソールに出力してくれるモジュール(elastalert_logger
)が標準で用意されているので、これをカスタムモジュールの冒頭にインポートします。
import dateutil.parser
from elastalert.ruletypes import RuleType
+ from elastalert.util import elastalert_logger
~~ 省略 ~~
コンソール出力処理の追加
モジュールをインポートしたら、elastalert_logger.info()
メソッドを任意の箇所に追加します。
ここでは、add_data()メソッド内のfor文
内でdocument[username]
を出力するようにします。
~~ 省略 ~~
def add_data(self, data):
for document in data:
+ elastalert_logger.info(document['username'])
# To access config options, use self.rules
if document['username'] in self.rules['usernames']:
# Convert the timestamp to a time object
login_time = document['@timestamp'].time()
# Convert time_start and time_end to time objects
time_start = dateutil.parser.parse(self.rules['time_start']).time()
time_end = dateutil.parser.parse(self.rules['time_end']).time()
# If the time falls between start and end
if login_time > time_start and login_time < time_end:
# To add a match, use self.add_match
self.add_match(document)
~~ 省略 ~~
出力結果
実行すると以下のデータがコンソールに出力されます。
admin
userXYZ
foobaz
コンソールに出力するには、ルールファイルのalert
オプションにdebug
が指定されている必要があります。
詳細は、ElastAlert公式のチュートリアルのexample_rules/example_login_rule.yaml
ファイルを参照ください。
まとめ
ElastAlertのカスタムルールで値をコンソールに出力には、次の2つをすることで実現できることを紹介しました。
- elastalert_loggerモジュールのインポート
- elastalert_logger.info()メソッドの追加